/**
 * 2021年7月31日 08:17:05 chanchaw
 * 生产计划登记页 - 车间使用
 * 生产计划登记序时表
 * 未完工表格
 * 两个表格的数据源来自同一个存储过程 - p_plan_report_registe_dtl_2
 *
 * 2023年2月14日 修改为使用存储过程 p_exec_plan_report_registe_dtl_2
 * 其中包含老版本的 “生产计划” 以及新版本的 “执行计划”，前者排序在前
 * 然后按照明细表的 serial_no 升序显示。
 * 在制作 “执行计划” 时根据数据源的字段 execPlan 判断调用原始请求还是 “执行计划” 的保存请求
 * 1. 表格ID = e_grid
 * 2. 定义函数：edatagrid - 初始化表格
 * 3. 修改表格数据的后台API - execPlanDetail/workshop/updateSelective
 * 4. 更换机台号会触发请求后端新的数据填充表格，函数：bindMachineChangeEvent
 * 5. 上面步骤4中的函数中请求后端 “未完工” 数据的后台API - execPlanMain/queryByMachineCode/
 *
 * 已完工表格ID = e_grid_finished定义函数：finisheddatagrid - 初始化表格
 * 点击 “日报” 弹出的模态窗的函数是 btn_barcode
 * 其中两个按钮“打印”，“保存”的打印都是调用该函数：justPrint
 *
 * 弹出模态窗点击“保存”会先执行多个验证性请求，实际操作数据的请求搜索下面的文字：
 * 制作 “执行计划” 之前的累计数量的请求是： salesPlanReportDtl/updateAccumulate
 * 行号大概再 2217.再制作 “执行计划” 后该请求应该根据数据源字段 execPlan 发送不同的请求
 * 0表示是“生产计划”请求 salesPlanReportDtl/updateAccumulate，1是执行话请求 execPlanDetail/updateAccumulate
 *
 * 打印现品票：
 * 点击“日报”模态窗的“保存”按钮执行的打印逻辑，搜索：“生产计划”和“执行计划”的数据，在原基础上新增两个参数：detailId，execPlan
 * 点击“日报”模态窗的“打印”按钮执行的打印逻辑，搜索：点击“日报”弹出的模态窗按钮“打印”执行的打印逻辑
 * 点击工具栏的“打印现品票”执行的逻辑，搜索：“打印现品票”按钮会及时获取选中行，这里不需调用getSelectedRow4Print，直接使用selected
 */
let productFile = {}; // 原票信息中根据存货编码到后台查询得到的表 product_file 数据
const DIALOG_ID_QRCODE = 'barcode_form';// 扫码用的弹出模态窗ID，搜索：id="barcode_form">

// 根据是否执行计划要动态调整请求后台的url
let urlDialogInit = '';// 点击工具栏按钮“日报”弹出模态窗时请求计划信息的 url
let urlDialogSave = '';// 点击模态窗保存按钮请求后台操作数据的 url
let urlDialogUpdateProjectName = '';
let urlFinish = '';// 完工请求
let urlFinishCancel = '';// 取消完工
let urlWorkshopUpdate = '';// 表格修改请求

let urlGridUFMove = '';// 未完工表格上下移动的请求
let urlGridFinishedPrintUpdate = '';// 已完工页面中打印后的修改请求
let urlUpdateSelectiveJson = '';
let urlGetSavePredata = '';
// let unFinishedSelectedRow = null;
let selectedRow4print = null;
$(function () {
    let superPrintButton = {id: 'btn_print_ticket', text: '打印现品票', iconCls: 'icon-print', onClick: btn_print_ticket, plain: true};
    if(!cheat4ScanCode()) $('#btn_print_ticket').linkbutton('disable');

    buttonGen('#btn_group', [
        {id: 'btn_modify', text: '修改', iconCls: 'icon-edit', onClick: btn_modify, plain: true},
        {id: 'btn_save', text: '保存', iconCls: 'icon-save', onClick: btn_save, plain: true},
        {
            id: 'btn_cancel_edit',
            text: '取消更改',
            iconCls: 'icon-application_delete',
            onClick: btn_cancel_edit,
            plain: true
        },
        {id: 'btn_export', text: '导出', iconCls: 'icon-page_excel', onClick: btn_export, plain: true},
        {id: 'btn_related', text: '关联入库', iconCls: 'icon-connect', onClick: btn_related, plain: true},
        {id: 'btn_barcode', text: '日报', iconCls: 'icon-script_code_red', onClick: btn_barcode, plain: true},
        superPrintButton,
        // {id: 'btn_print_ticket', text: '打印现品票', iconCls: 'icon-print', onClick: btn_print_ticket, plain: true},
        {id: 'updateFitQty', text: '修改入库数', iconCls: 'icon-connect', onClick: updateFitQty, plain: true},
        // {id: 'test01', text: '测试', iconCls: 'icon-connect', onClick: test01, plain: true},
        {id: 'btn_close', text: '关闭', iconCls: 'icon-no', onClick: btn_close, plain: true}
    ]);
    edatagrid();// 初始化“未完工”表格
    finisheddatagrid();// 初始化“已完工”表格
    bindEnterEvents()
    bindMachineChangeEvent();
    $(document).on('keydown', function (e) {
        let ctrl = e.ctrlKey;
        let alt = e.altKey;
        let shift = e.shiftKey;
        let keyCode = e.keyCode;
        if (ctrl && alt && shift && keyCode == 83) {
            $('input[controlled]').each(function (index, item) {
                if ($(item)['textbox']) {
                    $(item).textbox('textbox').attr('type', 'text');
                }
            })
        } else if (ctrl && alt && shift && keyCode == 72) {
            $('input[controlled]').each(function (index, item) {
                if ($(item)['textbox']) {
                    $(item).textbox('textbox').attr('type', 'password');
                }
            })
        }
    })
});

// 机台号变更导致更新表格数据
function bindMachineChangeEvent() {
    $('#machineCode').combobox({
        onChange: function (newVal, oldVal) {
            if (newVal == '') {
                $('#e_grid').datagrid('loadData', {total: 0, rows: []});
                $('#e_grid_finished').data('kendoGrid').dataSource.data([]);
                return;
            }
            if (newVal != oldVal) {
                $.messager.progress({title: '提示', msg: '数据加载中...', interval: 5000});
                // 根据机台号请求后端获取对应的生产计划数据，用于填充表格
                $.ajax({
                    url: `execPlanMain/queryByMachineCode/${newVal}`,
                    type: 'GET',
                    dataType: 'json',
                    success: function (data) {
                        $('#form').form('load', data);
                        if (data['detail'] != undefined) {
                            $('#e_grid').datagrid('loadData', data['detail']);
                        }
                        if (data['detailSub'] != undefined) {
                            $('#e_grid_finished').data('kendoGrid').dataSource.data(data['detailSub']);
                        }
                    },
                    complete: function () {
                        $.messager.progress('close');
                    }
                })
            }
        }
    })
}

/**
 * 加载表单
 * 2022年1月28日 13:57:26 chanchaw
 * 查询获取表达数据、未完工表格数据、已完工表格数据
 * @param id
 */
function loadForm(id) {
    $.ajax({
        url: `execPlanMain/queryByMachineCode/` + id,
        data: {},
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            if (!data) {
                $.messager.alert('提示', '该单据不存在!', 'warning');
                return;
            }
            let projectName = $('#projectName').combobox('getValue');
            if (projectName) {
                data.projectName = projectName;
            }
            $('#form').form('load', data);
            if (data['detail'] != undefined) { // 未完成表格加载数据
                $('#e_grid').datagrid('loadData', data['detail']);
            }
            if (data['detailSub'] != undefined) {
                $('#e_grid_finished').data('kendoGrid').dataSource.data(data['detailSub']);
            }
        }
    })
}

/**
 * 0：编辑状态
 * 1：已保存
 * 2：已审核
 * 3：已作废
 * @param state
 */
function setState(state = '0') {
    let tabTitle;
    if (window.top == window.self) {
        tabTitle = '计划登录页';
    } else {
        tabTitle = window.parent.getSelectedTabOptions().title;
    }
    let key = `${tabTitle}_state`;
    state = state.toString();
    switch (state) {
        case '0':
            $('#img_state').addClass('hidden');
            $('#e_grid').edatagrid('enableEditing');
            enableFormEdit($('#form'));
            $('#btn_group .easyui-linkbutton').each(function () {
                let title = $(this).linkbutton('options').text;
                if (['修改', '审核', '取消审核', '作废', '打印', /*'上张', '下张',*/ '导出'].indexOf(title) >= 0) {
                    $(this).linkbutton('disable');
                } else {
                    $(this).linkbutton('enable');
                }
            })
            break;
        case '1':
            $('#img_state').removeClass('img-delete img-audit img-cancel hidden');
            $('#img_state').addClass('img-save');
            $('#e_grid').edatagrid('disableEditing');
            disableFormEdit($('#form'));
            $('#btn_group .easyui-linkbutton').each(function () {
                let title = $(this).linkbutton('options').text;
                if (['新增单据', '修改', '审核', '打印', '作废', '上张', '下张', '导出', '关闭'].indexOf(title) >= 0) {
                    $(this).linkbutton('enable');
                } else {
                    $(this).linkbutton('disable');
                }
            })
            break;
        case '2':
            $('#img_state').removeClass('img-delete img-save img-cancel hidden');
            $('#img_state').addClass('img-audit');
            $('#e_grid').edatagrid('disableEditing');
            disableFormEdit($('#form'))
            $('#btn_group .easyui-linkbutton').each(function () {
                let title = $(this).linkbutton('options').text;
                if (['新增单据', '上张', '下张', '取消审核', '打印', '导出', '关闭'].indexOf(title) >= 0) {
                    $(this).linkbutton('enable');
                } else {
                    $(this).linkbutton('disable');
                }
            })
            break;
        case '3':
            $('#img_state').removeClass('img-delete img-audit img-save hidden');
            $('#img_state').addClass('img-cancel');
            $('#e_grid').edatagrid('disableEditing');
            disableFormEdit($('#form'))
            $('#btn_group .easyui-linkbutton').each(function () {
                let title = $(this).linkbutton('options').text;
                if (['新增单据', '上张', '下张', '关闭'].indexOf(title) >= 0) {
                    $(this).linkbutton('enable');
                } else {
                    $(this).linkbutton('disable');
                }
            })
            break;
    }
    window.sessionStorage.setItem(key, state.toString());
}

/**
 * 获取当前状态
 */
function getState() {
    let tabTitle;
    if (window.top == window.self) {
        tabTitle = '计划登录页';
    } else {
        tabTitle = window.parent.getSelectedTabOptions().title;
    }
    let key = `${tabTitle}_state`;
    return window.sessionStorage.getItem(key) || 0;
}

function pasteEvent(edg, editIndex) {
    function getDetailData(pfCoded) {
        if (!pfCoded) return {};
        let result = $.ajax({
            url: 'productFile/query',
            data: {pfCoded: pfCoded},
            method: 'GET',
            dataType: 'json',
            async: false
        })['responseJSON'];
        if (result && result.length > 0) {
            return result[0];
        } else {
            return {};
        }
    }

    let editors = $(edg).edatagrid('getEditors', editIndex) || [];
    editors = editors.filter(item => item['type'] != 'checkbox');
    for (let i = 0; i < editors.length; i++) {
        let editor = editors[i];
        if ($(editor.target)['textbox'] == undefined) continue;
        $(editor.target).textbox('textbox').bind('paste', function (e) {
            let clipboardData = e.originalEvent.clipboardData;
            let text = clipboardData.getData('Text');
            if (!text) return;
            let arr = text.split(/[\n]/);
            arr = arr.map(item => {
                let ms = item.split(/[\t]/);
                return ms.map(x => x.replace(/[\t\s]/, ''));
            })
            for (let j = 0; j < arr.length; j++) {
                let excelRow = arr[j];
                if (j == 0) {
                    for (let k = 0; k < excelRow.length; k++) {
                        if (i + k <= editors.length - 1)
                            $(editors[i + k].target)[editors[i + k].type]('setValue', excelRow[k]);
                    }
                } else {
                    for (let k = 0; k < excelRow.length; k++) {
                        if (i + k <= editors.length - 1) {
                            let allRows = $(edg).edatagrid('getRows');
                            let r = {}
                            r.index = editIndex + j;
                            let modifyRow = {};
                            if (editors[i + k]['field'] == 'productCode') {
                                modifyRow[editors[i + k]['field']] = excelRow[k];
                                let rec = getDetailData(excelRow[k]);
                                if (rec) {
                                    modifyRow.specification = rec['pfSpecification'];
                                    modifyRow.unitType = rec['unitType'];
                                    modifyRow.productName = rec['pfName'];
                                }
                                r.row = modifyRow;
                            } else {
                                modifyRow[editors[i + k]['field']] = excelRow[k];
                                r.row = modifyRow;
                            }
                            if (allRows.length - 1 > editIndex + j) {
                                $(edg).datagrid('updateRow', r);
                            } else {
                                $(edg).datagrid('insertRow', r);
                            }
                        }
                    }
                }
            }
            return false;
        })
    }
}

/**
 * 2021年8月19日 13:21:41 chanchaw
 * 初始化未完工表格
 * 2023年2月12日 修改为 “执行计划” 数据，之前是 “生产计划”数据
 */
function edatagrid() {
    let currentEditIndex = undefined;
    const SUFFIX = '_unfinished';
    $('#e_grid').datagrid({ // 未完工表格请求数据
        data: [],
        // updateUrl: 'execPlanDetail/workshop/updateSelective',
        updateUrl: urlWorkshopUpdate,
        striped: true,
        fit: true,
        sortable: true,
        rownumbers: true,
        remoteSort: false,
        showFooter: true,
        singleSelect: true,
        destroyMsg: {
            norecord: {
                title: '警告',
                msg: '未选中任何数据'
            },
            confirm: {
                title: '确认',
                msg: '确定删除吗?删除后不可恢复!'
            }
        },
        columns: [[
            {title: '编号', field: 'id', hidden: true, width: 50, align: 'center', halign: 'center'},
            {title: 'fk', field: 'parentId', hidden: true, width: 50, align: 'center', halign: 'center'},
            {title: 'execPlan', field: 'execPlan', hidden: true, width: 50, align: 'center', halign: 'center'},
            {
                title: '销售订单号',
                field: 'salesOrderCode',
                width: 100,
                align: 'center',
                halign: 'center',
            },
            /*{
                title: '计划单号',
                field: 'planCode',
                width: 200,
                align: 'center',
                halign: 'center',
                sortable: true,
            },*/
            /*{
                title: '工程名',
                field: 'projectName',
                width: 200,
                align: 'center',
                halign: 'center',
                sortable: true,
            },*/
            {
                title: '生产日期',
                field: 'planDate',
                width: 200,
                align: 'center',
                halign: 'center',
            },
            {
                title: '存货编码',
                field: 'productCode',
                width: 200,
                align: 'center',
                halign: 'center',
                formatter:function(val,item,rowIndex){
                    if(item.hash_string){
                        // 下载时默认的文件名称
                        const downloadFileName = getDownloadFileName(item);
                        // 拼接图纸目录和UUID文件名，得到图纸的绝对路径文件名
                        const drawingLink = getDrawingFileLink(item['hashString']);
                        return `<div align="center" style="width:100%;"><a href=${drawingLink} target="view_window" download=${downloadFileName}> &nbsp;` + item.productCode +`&nbsp; </a></div>`;
                    }
                    else {
                        return item.productCode;
                    }
                },
            },
            {
                title: '存货名称',
                field: 'productName',
                width: 200,
                align: 'left',
                halign: 'center',
            },
            {
                title: '客户名称',
                field: 'clientName',
                width: 220,
                align: 'center',
                halign: 'center',
            },
            // {
            //     title: '客户名称',
            //     field: 'clientName_unfinished',
            //     width: 220,
            //     align: 'center',
            //     halign: 'center',
            //     hidden: true,
            // },
            {
                title: '打样',
                field: 'canProvideSample',
                width: 100,
                align: 'center',
                halign: 'center',
                hidden: true,
                formatter: (v, r, i) => `<input readonly="readonly" type="checkbox" onclick="return false;" ${v ? 'checked' : ''}>`,
            },
            {
                title: '规格型号',
                field: 'specification',
                width: 150,
                align: 'center',
                halign: 'center',
                editor: {type: 'textbox', options: {editable: false}}
            },
            {
                title: '印版编号',
                field: 'plateCode',
                width: 100,
                align: 'center',
                halign: 'center',
                editor: {type: 'textbox', options: {editable: false}}
            },
            {
                title: '计划数量',
                field: 'planQty',
                width: 100,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(0) : '';
                },
                editor: {type: 'numberbox', options: {required: true, precision: 0}}
            },
            {
                title: '备注',
                field: 'remarks',
                width: 150,
                align: 'center',
                halign: 'center',
                editor: {type: 'textbox', options: {editable: false}}
            },
            {
                title: '贴合数量',
                field: 'fitQty',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(0) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 0}}
            },
            {
                title: '良品数量',
                field: 'qualifiedQty',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(0) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 0}}
            },
            {
                title: '不良数量',
                field: 'defectiveQty',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(0) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 0}}
            },
            {
                title: '停机次数',
                field: 'stopQty',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(0) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 0}}
            },
            {
                title: '发货计划日期',
                field: 'sendOutDate',
                width: 120,
                align: 'center',
                halign: 'center',
            },
            // {
            //     title: '1',
            //     field: 'param1',
            //     width: 60,
            //     align: 'right',
            //     halign: 'center',
            //     formatter: (v, r, i) => {
            //         return v ? parseFloat(v).toFixed(1) : '';
            //     },
            //     editor: {type: 'numberbox', options: {required: false, precision: 1}}
            // },
            // {
            //     title: '2',
            //     field: 'param2',
            //     width: 60,
            //     align: 'right',
            //     halign: 'center',
            //     formatter: (v, r, i) => {
            //         return v ? parseFloat(v).toFixed(1) : '';
            //     },
            //     editor: {type: 'numberbox', options: {required: false, precision: 1}}
            // },
            // {
            //     title: '3',
            //     field: 'param3',
            //     width: 60,
            //     align: 'right',
            //     halign: 'center',
            //     formatter: (v, r, i) => {
            //         return v ? parseFloat(v).toFixed(1) : '';
            //     },
            //     editor: {type: 'numberbox', options: {required: false, precision: 1}}
            // },
            // {
            //     title: '4',
            //     field: 'param4',
            //     width: 60,
            //     align: 'right',
            //     halign: 'center',
            //     formatter: (v, r, i) => {
            //         return v ? parseFloat(v).toFixed(1) : '';
            //     },
            //     editor: {type: 'numberbox', options: {required: false, precision: 1}}
            // },
            // {
            //     title: '5',
            //     field: 'param5',
            //     width: 60,
            //     align: 'right',
            //     halign: 'center',
            //     formatter: (v, r, i) => {
            //         return v ? parseFloat(v).toFixed(1) : '';
            //     },
            //     editor: {type: 'numberbox', options: {required: false, precision: 1}}
            // },
            // {
            //     title: '6',
            //     field: 'param6',
            //     width: 60,
            //     align: 'right',
            //     halign: 'center',
            //     formatter: (v, r, i) => {
            //         return v ? parseFloat(v).toFixed(1) : '';
            //     },
            //     editor: {type: 'numberbox', options: {required: false, precision: 1}}
            // },
            // {
            //     title: '7',
            //     field: 'param7',
            //     width: 60,
            //     align: 'right',
            //     halign: 'center',
            //     formatter: (v, r, i) => {
            //         return v ? parseFloat(v).toFixed(1) : '';
            //     },
            //     editor: {type: 'numberbox', options: {required: false, precision: 1}}
            // },
            // {
            //     title: '8',
            //     field: 'param8',
            //     width: 60,
            //     align: 'right',
            //     halign: 'center',
            //     formatter: (v, r, i) => {
            //         return v ? parseFloat(v).toFixed(1) : '';
            //     },
            //     editor: {type: 'numberbox', options: {required: false, precision: 1}}
            // },
            // {
            //     title: '9',
            //     field: 'param9',
            //     width: 60,
            //     align: 'right',
            //     halign: 'center',
            //     formatter: (v, r, i) => {
            //         return v ? parseFloat(v).toFixed(1) : '';
            //     },
            //     editor: {type: 'numberbox', options: {required: false, precision: 1}}
            // },
            // {
            //     title: '10',
            //     field: 'param10',
            //     width: 60,
            //     align: 'right',
            //     halign: 'center',
            //     formatter: (v, r, i) => {
            //         return v ? parseFloat(v).toFixed(1) : '';
            //     },
            //     editor: {type: 'numberbox', options: {required: false, precision: 1}}
            // },
            
            // 不良原因
            {
                title: '1.开机调试',
                field: 'flaw0101',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '2.1纸板卡破 - 设定异常',
                field: 'flaw0201',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '2.2纸板卡破 - 纸板弯翘',
                field: 'flaw0202',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '3.1印刷跑位 - 设定异常',
                field: 'flaw0301',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '3.2印刷跑位 - 纸板弯翘',
                field: 'flaw0302',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '4.1模切跑位 - 设定异常',
                field: 'flaw0401',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '4.2模切跑位 - 纸板弯翘',
                field: 'flaw0402',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '5.1开槽跑位 - 设定异常',
                field: 'flaw0501',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '5.2开槽跑位 - 纸板弯翘',
                field: 'flaw0502',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '6.1印刷不良 - 色差',
                field: 'flaw0601',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '6.2印刷不良 - 印刷不匀',
                field: 'flaw0602',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '6.3印刷不良 - 印刷露底',
                field: 'flaw0603',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '6.4印刷不良 - 印版开胶',
                field: 'flaw0604',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '6.5印刷不良 - 缺失、重影',
                field: 'flaw0605',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '6.6印刷不良 - 批次错误',
                field: 'flaw0606',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '7.1压线跑位 - 设定异常',
                field: 'flaw0701',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '7.2压线跑位 - 纸板弯翘',
                field: 'flaw0702',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '8.1纸板爆线 - 面纸爆线',
                field: 'flaw0801',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '8.2纸板爆线 - 底纸爆线',
                field: 'flaw0802',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '9.1纸板脏污 - 面纸脏污',
                field: 'flaw0901',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '9.2纸板脏污 - 底纸脏污',
                field: 'flaw0902',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '9.3纸板脏污 - 接头线',
                field: 'flaw0903',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '10.反投料',
                field: 'flaw1001',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '11.打包破损',
                field: 'flaw1101',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '12.1粘合不良 - 粘箱错位',
                field: 'flaw1201',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '12.2粘合不良 - 内粘连',
                field: 'flaw1202',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '12.3粘合不良 - 胶外溢',
                field: 'flaw1203',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '12.4粘合不良 - 开胶',
                field: 'flaw1204',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '12.5粘合不良 - 粘合异物混入',
                field: 'flaw1205',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            },
            {
                title: '13.其他',
                field: 'flaw1301',
                width: 60,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(1) : '';
                },
                editor: {type: 'numberbox', options: {required: false, precision: 1}}
            }
        ]],
        onLoadSuccess: function (data) {
            $(this).datagrid('enableFilter');
            let rows = data.rows;
            $(this).datagrid('reloadFooter', [{
                salesOrderCode: '合计',
                planQty: cal(rows, 'planQty'),
                fitQty: cal(rows, 'fitQty'),
                qualifiedQty: cal(rows, 'qualifiedQty'),
                defectiveQty: cal(rows, 'defectiveQty'),
                stopQty: cal(rows, 'stopQty'),
            }])

            function cal(arr, field) {
                return arr.reduce(function (prev, curr) {
                    return prev += (curr[field] ? parseFloat(curr[field]) : 0);
                }, 0);
            }
        },
        onBeforeLoad: function (param) {
            $(this).datagrid('destroyFilter');
            return true;
        },
        onEdit: function (index, row) {
            currentEditIndex = index;
            let prepareTime = $(this).edatagrid('getEditor', {
                index: index,
                field: 'prepareTime'
            });
            if (prepareTime != undefined && !$(prepareTime.target).datebox('getValue')) {
                $(prepareTime.target).datebox('setValue', getCurrentDate(5));
            }
            //绑定粘贴事件
            pasteEvent(this, index);
            bindInputEvents(this, index);
        },
        onAdd: function (index, row) {
            currentEditIndex = index;
            //绑定粘贴事件
            pasteEvent(this, index);
            bindInputEvents(this, index);
        },
        onSave: function (index, row) {
            currentEditIndex = undefined;
        },
        onSuccess: function (index, row) {
            if (!row.success) {
                $.messager.alert('提示', row.message, 'warning');
                $(this).datagrid('rejectChanges');
            } else {
                $.messager.show({title: '提示', msg: row.message});
            }
        },
        onResizeColumn: function (f, w) {
            columnResizeEvent($('body').data('menu_id'), f, w, undefined, undefined, SUFFIX);
        },
        onHeaderContextMenu: function (e, field) {
            e.preventDefault();
            let div = `<div id="header_context_menu">
                            <div data-options="iconCls:'icon-cancel'">取消更改</div>
                            <div data-options="iconCls:'icon-edit'">确定更改</div>
                        </div>`;
            if ($('#header_context_menu').length <= 0) {
                $(div).appendTo($('body'));
                $('#header_context_menu').menu({
                    onClick: function (item) {
                        let name = item.text;
                        switch (name) {
                            case '取消更改':
                                $('#e_grid').edatagrid('cancelRow');
                                break;
                            case '确定更改':
                                $('#e_grid').edatagrid('saveRow');
                                break;
                        }
                    }
                })
            }
            $('#header_context_menu').menu('show', {
                top: e.pageY,
                left: e.pageX
            })
        },
        onRowContextMenu: function (e, rowIndex, rowData) {
            let datagrid = $(this);
            e.preventDefault();
            datagrid.datagrid('clearSelections');
            datagrid.datagrid('selectRow', rowIndex);
            let div = `<div id="row_context_menu">
                            <div data-options="iconCls:'icon-arrow_up'">上移</div>
                            <div data-options="iconCls:'icon-arrow_down'">下移</div>
                            <div data-options="iconCls:'icon-arrow_redo'">置顶</div>
                            <div data-options="iconCls:'icon-arrow_undo'">置底</div>
                            <div data-options="iconCls:'icon-user_gray'">完工</div>
                        </div>`;
            if ($('#row_context_menu').length <= 0) {
                $(div).appendTo($('body'));
            }
            $('#row_context_menu').menu({
                onClick: function (item) {
                    let name = item.text;
                    let selected = datagrid.datagrid('getSelected');
                    if (selected == undefined) {
                        $.messager.alert('提示', '未选中网格行', 'warning');
                        return;
                    }
                    refreshApi(selected);
                    let selectRowIndex = rowIndex;
                    switch (name) {
                        case '上移':
                            if (selectRowIndex > 0) {
                                // $.post(`execPlanDetail/move/${selected.id}/${-1}`, {}, data => {
                                $.post(`${urlGridUFMove}/${selected.id}/${-1}`, {}, data => {
                                    if (!data.success) {
                                        $.messager.alert('提示', data.message, 'warning');
                                        return;
                                    }
                                    datagrid.datagrid('deleteRow', selectRowIndex);
                                    datagrid.datagrid('insertRow', {
                                        index: --selectRowIndex,
                                        row: selected
                                    });
                                    resetIndex(datagrid, datagrid.datagrid('getRows') || [])
                                    datagrid.datagrid('selectRow', selectRowIndex);
                                }, 'json');
                            }
                            break;
                        case '下移':
                            if (selectRowIndex < datagrid.datagrid('getRows').length - 1) {
                                // $.post(`execPlanDetail/move/${selected.id}/${1}`, {}, data => {
                                $.post(`${urlGridUFMove}/${selected.id}/${1}`, {}, data => {
                                    if (!data.success) {
                                        $.messager.alert('提示', data.message, 'warning');
                                        return;
                                    }
                                    datagrid.datagrid('deleteRow', selectRowIndex);
                                    datagrid.datagrid('insertRow', {
                                        index: ++selectRowIndex,
                                        row: selected
                                    });
                                    resetIndex(datagrid, datagrid.datagrid('getRows') || [])
                                    datagrid.datagrid('selectRow', selectRowIndex);
                                }, 'json');

                            }
                            break;
                        case '置顶':
                            if (selectRowIndex > 0) {
                                // $.post(`execPlanDetail/move/${selected.id}/${-9999}`, {}, data => {
                                $.post(`${urlGridUFMove}/${selected.id}/${-9999}`, {}, data => {
                                    if (!data.success) {
                                        $.messager.alert('提示', data.message, 'warning');
                                        return;
                                    }
                                    datagrid.datagrid('deleteRow', selectRowIndex);
                                    datagrid.datagrid('insertRow', {
                                        index: 0,
                                        row: selected
                                    });
                                    resetIndex(datagrid, datagrid.datagrid('getRows') || [])
                                    datagrid.datagrid('selectRow', 0);
                                }, 'json');
                            }
                            break;
                        case '置底':
                            if (selectRowIndex < datagrid.datagrid('getRows').length - 1) {
                                // $.post(`execPlanDetail/move/${selected.id}/${9999}`, {}, data => {
                                $.post(`${urlGridUFMove}/${selected.id}/${9999}`, {}, data => {
                                    if (!data.success) {
                                        $.messager.alert('提示', data.message, 'warning');
                                        return;
                                    }
                                    let length = datagrid.datagrid('getRows').length - 1;
                                    datagrid.datagrid('deleteRow', selectRowIndex);
                                    datagrid.datagrid('insertRow', {
                                        index: length,
                                        row: selected
                                    });
                                    resetIndex(datagrid, datagrid.datagrid('getRows') || [])
                                    datagrid.datagrid('selectRow', length);
                                }, 'json');
                            }
                            break;
                        case "完工":
                            $.messager.progress({title: '正在提交...', interval: 500});
                            $.ajax({
                                // url: 'execPlanMain/finished',
                                url: urlFinish,
                                type: 'POST',
                                dataType: 'json',
                                data: {id: selected.id},
                                success: function (data) {
                                    if (data.success) {
                                        loadForm($('#machineCode').combobox('getValue'));
                                        $.messager.show({
                                            title: '提示',
                                            msg: data.message
                                        })
                                    } else {
                                        $.messager.alert('提示', data.message, 'warning');
                                    }
                                },
                                complete: function () {
                                    $.messager.progress('close');
                                }
                            })
                            break;
                    }
                }
            })

            function resetIndex(grid, rows) {
                let i = 0;
                let r = rows.map(item => {
                    item['serialNo'] = ++i;
                    return item;
                })
                $(grid).datagrid('loadData', [...r]);
            }

            $('#row_context_menu').menu('show', {
                top: e.pageY,
                left: e.pageX
            })
        }
    });
    //$('#e_grid').edatagrid('enableEditing');
    setDatagridColumnOpts($('body').data('menu_id'), $('#e_grid'), undefined, undefined, SUFFIX);
}

// 初始化已完工表格
function finisheddatagrid() {
    const SUFFIX = '_finished';
    let dataSource = new kendo.data.DataSource({
        schema: {
            model: {
                id: 'id',
                fields: {
                    planDate: {type: "date"},
                    inboundDate: {type: "date"},
                    sendOutDate: {type: "date"},
                    planQty: {type: "number"},
                    fitQty: {type: "number"},
                    qualifiedQty: {type: "number"},
                    defectiveQty: {type: "number"},
                    stopQty: {type: "number"},
                }
            }
        },
        aggregate: [
            {field: "planQty", aggregate: "sum"},
            {field: "fitQty", aggregate: "sum"},
            {field: "qualifiedQty", aggregate: "sum"},
            {field: "defectiveQty", aggregate: "sum"},
            {field: "stopQty", aggregate: "sum"},
        ],
        change: function (e) {
            let filtrer = this.filter();
            let allData = this.data();
            let query = new kendo.data.Query(allData);
            let data = query.filter(filtrer).data;
        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('disable')
                }
            })
            $('body').find('th a[class="k-grid-filter"]').css({display: 'none'});
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('enable')
                }
            })
            $('body').find('th a[class="k-grid-filter"]').css({display: 'none'});
        }
    });
    let columns = [
        {field: "no", title: "序号", filterable: false, template: "<span class='row_number'></span>", width: 40},
        {
            title: '编号',
            field: 'id',
            hidden: true,
            width: 50,
            align: 'center',
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'}
        },
        {
            title: '主键',
            field: 'parentId',
            hidden: true,
            width: 50,
            align: 'center',
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'}
        },
        {
            title: '销售订单号',
            field: 'salesOrderCode',
            width: 100,
            align: 'center',
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        },
        /*{
            title: '工程名',
            field: 'projectName',
            width: 100,
            align: 'center',
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            template: item => item['projectName'] ? item['projectName'] : ''
        },*/
        /*{
            title: '计划单号',
            field: 'planCode',
            width: 200,
            align: 'center',
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        },*/
        {
            title: '生产计划日期',
            field: 'planDate',
            width: 200,
            align: 'center',
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        },
        {
            title: '入库日期',
            field: 'inboundDate',
            width: 200,
            align: 'center',
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        },
        {
            title: '存货编码',
            field: 'productCode',
            width: 200,
            align: 'center',
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        },
        {
            title: '存货名称',
            field: 'productName',
            width: 200,
            align: 'center',
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;text-align:left;'},
        },
        {
            title: '客户名称',
            field: 'clientName',
            width: 220,
            align: 'center',
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            editor: {type: 'textbox', options: {required: false, editable: false}}
        },
        // {
        //     title: '客户名称',
        //     field: 'clientName_finished',
        //     width: 220,
        //     align: 'center',
        //     hidden: true,
        //     headerAttributes: {style: 'text-align:center;'},
        //     attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        //     editor: {type: 'textbox', options: {required: false, editable: false}}
        // },
        {
            title: '打样',
            field: 'canProvideSample',
            width: 100,
            align: 'center',
            hidden: true,
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            template: v => `<input readonly="readonly" type="checkbox" onclick="return false;" ${v['canProvideSample'] ? 'checked' : ''}>`,
        },
        {
            title: '规格型号',
            field: 'specification',
            width: 150,
            align: 'center',
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        },
        {
            title: '印版编号',
            field: 'plateCode',
            width: 100,
            align: 'center',
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        },
        {
            title: '计划数量',
            field: 'planQty',
            width: 100,
            align: 'right',
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            template: v => {
                return v['planQty'] ? parseFloat(v['planQty']).toFixed(0) : '';
            },
            footerTemplate: '#=kendo.format("{0:n0}",sum)#',
        },
        {
            title: '贴合数量',
            field: 'fitQty',
            width: 60,
            align: 'right',
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            template: v => {
                return v['fitQty'] ? parseFloat(v['fitQty']).toFixed(0) : '';
            },
            footerTemplate: '#=kendo.format("{0:n0}",sum)#',
        },
        {
            title: '良品数量',
            field: 'qualifiedQty',
            width: 60,
            align: 'right',
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            template: v => {
                return v['qualifiedQty'] ? parseFloat(v['qualifiedQty']).toFixed(0) : '';
            },
            footerTemplate: '#=kendo.format("{0:n0}",sum)#',
        },
        {
            title: '不良数量',
            field: 'defectiveQty',
            width: 60,
            align: 'right',
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            template: v => {
                return v['defectiveQty'] ? parseFloat(v['defectiveQty']).toFixed(0) : '';
            },
            footerTemplate: '#=kendo.format("{0:n0}",sum)#',
        },
        {
            title: '停机次数',
            field: 'stopQty',
            width: 60,
            align: 'right',
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
            template: v => {
                return v['stopQty'] ? parseFloat(v['stopQty']).toFixed(0) : '';
            },
            footerTemplate: '#=kendo.format("{0:n0}",sum)#',
        },
        {
            title: '发货计划日期',
            field: 'sendOutDate',
            width: 120,
            align: 'center',
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'},
        },
        {
            title: '1.开机调试',
            field: 'flaw0101',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '2.1纸板卡破 - 设定异常',
            field: 'flaw0201',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '2.2纸板卡破 - 纸板弯翘',
            field: 'flaw0202',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '3.1印刷跑位 - 设定异常',
            field: 'flaw0301',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '3.2印刷跑位 - 纸板弯翘',
            field: 'flaw0302',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '4.1模切跑位 - 设定异常',
            field: 'flaw0401',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '4.2模切跑位 - 纸板弯翘',
            field: 'flaw0402',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '5.1开槽跑位 - 设定异常',
            field: 'flaw0501',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '5.2开槽跑位 - 纸板弯翘',
            field: 'flaw0502',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '6.1印刷不良 - 色差',
            field: 'flaw0601',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '6.2印刷不良 - 印刷不匀',
            field: 'flaw0602',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '6.3印刷不良 - 印刷露底',
            field: 'flaw0603',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '6.4印刷不良 - 印版开胶',
            field: 'flaw0604',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '6.5印刷不良 - 缺失、重影',
            field: 'flaw0605',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '6.6印刷不良 - 批次错误',
            field: 'flaw0606',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '7.1压线跑位 - 设定异常',
            field: 'flaw0701',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '7.2压线跑位 - 纸板弯翘',
            field: 'flaw0702',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '8.1纸板爆线 - 面纸爆线',
            field: 'flaw0801',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '8.2纸板爆线 - 底纸爆线',
            field: 'flaw0802',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '9.1纸板脏污 - 面纸脏污',
            field: 'flaw0901',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '9.2纸板脏污 - 底纸脏污',
            field: 'flaw0902',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '9.3纸板脏污 - 接头线',
            field: 'flaw0903',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '10.反投料',
            field: 'flaw1001',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '11.打包破损',
            field: 'flaw1101',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '12.1粘合不良 - 粘箱错位',
            field: 'flaw1201',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '12.2粘合不良 - 内粘连',
            field: 'flaw1202',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '12.3粘合不良 - 胶外溢',
            field: 'flaw1203',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '12.4粘合不良 - 开胶',
            field: 'flaw1204',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '12.5粘合不良 - 粘合异物混入',
            field: 'flaw1205',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        },
        {
            title: '13.其他',
            field: 'flaw1301',
            width: 60,
            align: 'right',
            halign: 'center',
            formatter: (v, r, i) => {
                return v ? parseFloat(v).toFixed(1) : '';
            },
            editor: {type: 'numberbox', options: {required: false, precision: 1}}
        }
    ];
    let grid = $("#e_grid_finished").kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: {
            extra: false
        },
        dataSource: dataSource,
        columnMenu: false,
        excel: {
            fileName: "已完工.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        height: '99%',
        pageable: {
            pageSize: 200
        },
        reorderable: true,
        dataBound: function () {
            let rows = this.items();
            $(rows).each(function () {
                let index = $(this).index() + 1;
                let rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
            });
        },
        columnHide: function (e) {
            //列隐藏事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field + SUFFIX, null, true, null);
        },
        columnShow: function (e) {
            //列显示事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field + SUFFIX, null, false, null);
        },
        columnResize: function (e) {
            //  列伸缩事件
            let field = e.column.field;
            let newWidth = e.newWidth;
            if (newWidth < 20) {
                columnResizeEvent($('body').data('menu_id'), field + SUFFIX, null, true, null);
            } else {
                columnResizeEvent($('body').data('menu_id'), field + SUFFIX, newWidth, null, null);
            }
        },
        columnReorder: function (e) {
            //  列拖动事件
            let newColumns = JSON.parse(JSON.stringify(e.sender.columns))
            newColumns = reorder(newColumns, e.oldIndex, e.newIndex);
            let menuId = $('body').data('menu_id');
            let col = []
            for (let i = 0; i < newColumns.length; i++) {
                if (newColumns[i]['field'])
                    col.push({
                        serialNum: i,
                        sysMenuId: menuId,
                        field: newColumns[i]['field'] + SUFFIX
                    });
            }
            $.ajax({
                url: 'sysUserTableConfig/modify/reorder',
                contentType: 'application/json',
                data: JSON.stringify(col),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                }
            })
        },
    });
    let grid01 = $('#e_grid_finished').data('kendoGrid');
    loadOptions(grid01, columns, SUFFIX, $('body').data('menu_id'));// 已完工表格设置列样式
    $('body').on('mouseenter', 'th', function (e) {
        $('.k-grid-filter').finish();
        $(this).find('.k-grid-filter').fadeIn();
    })
    grid.on('contextmenu', 'tr', function (e) {
        e.preventDefault();
        let kGrid = $('#e_grid_finished').data('kendoGrid');
        kGrid.clearSelection();
        kGrid.select(this);
        let row = kGrid.select();
        let selected = kGrid.dataItem(row);
        let div = `<div id="row_context_menu_sub">
                            <div data-options="iconCls:'icon-user_red'">取消完工</div>
                            <div data-options="iconCls:'icon-user_red'">复制行</div>
                        </div>`;
        if ($('#row_context_menu_sub').length <= 0) {
            $(div).appendTo($('body'));
        }
        $('#row_context_menu_sub').menu({
            onClick: function (item) {
                let name = item.text;
                if (selected == undefined) {
                    $.messager.alert('提示', '未选中网格行', 'warning');
                    return;
                }
                refreshApi(selected);
                switch (name) {
                    case "取消完工":
                        $.messager.progress({title: '正在提交...', interval: 500});
                        $.ajax({
                            // url: 'execPlanMain/finished/cancel',
                            url: urlFinishCancel,
                            type: 'POST',
                            dataType: 'json',
                            data: {id: selected.id},
                            success: function (data) {
                                if (data.success) {
                                    loadForm($('#machineCode').combobox('getValue'));
                                    $.messager.show({
                                        title: '提示',
                                        msg: data.message
                                    })
                                } else {
                                    $.messager.alert('提示', data.message, 'warning');
                                }
                            },
                            complete: function () {
                                $.messager.progress('close');
                            }
                        })
                        break;
                    case "复制行":
                        copyRows('e_grid_finished');
                        break;
                }
            }
        })
        $('#row_context_menu_sub').menu('show', {
            top: e.pageY,
            left: e.pageX
        })
    });
    $('body').on('mouseleave', 'th', function (e) {
        $(this).find('.k-grid-filter').fadeOut();
    })
}

function onTabSelect(title, index) {
    setTimeout(function () {
        switch (index) {
            case 0:
                $('#btn_print_ticket').linkbutton('disable');
                $('#updateFitQty').linkbutton('disable');
                break;
            case 1:
                if(cheat4ScanCode())
                    $('#btn_print_ticket').linkbutton('enable');
                $('#updateFitQty').linkbutton('enable');
                let kGrid = $('#e_grid_finished').data('kendoGrid');
                if (kGrid != undefined) {
                    kGrid.refresh();
                }
                break;
        }
    }, 0)
}

//  保存单据
function btn_save() {
    $('#e_grid').edatagrid('saveRow');
}

//  取消更改
function btn_cancel_edit() {
    $('#e_grid').edatagrid('cancelRow');
}

//  修改
function btn_modify() {
    if (getState() == '1') {
        //setState(0);
    }
}

//  打印 - 点击日报弹出的模态窗中“打印” 和 “保存” 都会用到的打印功能
function justPrint() {
    let formData = $('#barcode_form').serializeObject();
    let fitQty = formData['fitQty'] ? parseFloat(formData['fitQty']) : 0;
    let qualifiedQty = formData['qualifiedQty'] ? parseFloat(formData['qualifiedQty']) : 0;
    let printQty = formData['printQty'] ? parseFloat(formData['printQty']) : 0;
    let id = formData['id'];
    // 2021年7月15日 09:31:14 chanchaw 追加检测贴合数量必须大于0
    if (!fitQty || parseFloat(fitQty).toFixed(1) <= 0) {
        $.messager.alert('提示', '贴合数量必须输入!', 'warning');
        $('#barcode_form').find('input[textboxname="fitQty"]').textbox('textbox').focus();
        return;
    }

    // 2021年7月15日 09:31:14 chanchaw 追加检测良品数量必须大于0
    if (!qualifiedQty || parseFloat(qualifiedQty).toFixed(1) <= 0) {
        $.messager.alert('提示', '良品数量必须输入!', 'warning');
        $('#barcode_form').find('input[textboxname="qualifiedQty"]').textbox('textbox').focus();
        return;
    }

    // 2021年7月15日 09:31:14 chanchaw 追加检测打印数量必须大于0
    if (!printQty || parseFloat(printQty).toFixed(1) <= 0) {
        $.messager.alert('提示', '打印张数必须输入!', 'warning');
        $('#barcode_form').find('input[textboxname="printQty"]').textbox('textbox').focus();
        return;
    }
    if (fitQty < qualifiedQty) {
        $.messager.alert('提示', '良品数不可大于贴合数！!', 'warning');
        return;
    }
    let postdata = {
        id: id,
        fitQty: fitQty,
        qualifiedQty: qualifiedQty,
        printQty: printQty,
    };
    let productCoded = $('#barcode_form').serializeObject()['productCoded'];
    let tinyTagId = '';
    $.ajax({
        url: 'productFile/queryMessageByPfCode/' + productCoded,
        dataType: 'json',
        type: 'GET'
    }).then(function (data) {
        if (data != undefined) {
            // 存货档案中设置了强制扫码，则要检测扫描二维码是否通过
            if(!cheat4ScanCode())
                if (data['canScanCode']) {
                    if (!$('#barcode_form').form('validate')) {
                        $.messager.alert('提示', '校验失败!禁止保存!', 'error');
                        return;
                    }
                }

            //  执行打印
            // 1. 设置打印现品票参数
            let printParam = [];
            // 点击“日报”弹出的模态窗按钮“打印”执行的打印逻辑
            // 由于新增了执行计划要在原基础上新增参数
            getSelectedRow4Print();// 获取当前选中行的数据
            for (let i = 0; i < printQty; i++) {
                printParam.push({
                    reportlet: formData['tagPath'],
                    id: id,
                    detailId: id,
                    execPlan: selectedRow4print.execPlan
                })
            }
            // console.log('1692现品票打印参数：',formData['tagPath'],id)

            // 2. 设置打印小标签参数
            tinyTagId = data['tinyTagId'] || '';
            if (tinyTagId) {
                $.ajax({ // 请求获取小标签报表文件地址
                    url: 'tagLibrary/queryByPk/' + tinyTagId,
                    dataType: 'json', type: 'GET',
                    async: false
                }).then(function (record) {
                    const tagPath = record['tagPath'];// 获取报表文件地址：tags/TOTO_tiny.cpt
                    const category = record['category'];
                    const rptParam = getRptParam(tagPath,id,productCoded,category,selectedRow4print.execPlan);
                    // console.log('1692小标签打印参数：',rptParam);
                    printParam.push(rptParam);
                    // 2021年10月11日 09:36:35 注释下面代码，采用上面
                    // 是 “TOTO_tiny.cpt” 则传递不同的参数，其他产品标签都传递存货编码
                    // printParam.push({
                    //     reportlet: record['tagPath'],
                    //     pfCoded: productCoded
                    // })
                })
            }
            printFn(printParam);
        }
    }, () => {
        $.messager.alert('提示', '服务器连接失败!', 'error');
    });
}



//  保存并打印 - 点击日报弹出的模态窗 “保存” 按钮执行的逻辑
function saveAndPrint(projectName, registerEmployeeId, selected, afterPrinting) {
    let formData = $('#barcode_form').serializeObject();
    let fitQty = formData['fitQty'] ? parseFloat(formData['fitQty']) : 0;
    let qualifiedQty = formData['qualifiedQty'] ? parseFloat(formData['qualifiedQty']) : 0;
    let printQty = formData['printQty'] ? parseFloat(formData['printQty']) : 0;
    let id = formData['id'];
    // 2021年7月15日 09:31:14 chanchaw 追加检测贴合数量必须大于0
    if (!fitQty || parseFloat(fitQty).toFixed(1) <= 0) {
        $.messager.alert('提示', '贴合数量必须输入!', 'warning');
        $('#barcode_form').find('input[textboxname="fitQty"]').textbox('textbox').focus();
        return;
    }

    // 2021年7月15日 09:31:14 chanchaw 追加检测良品数量必须大于0
    if (!qualifiedQty || parseFloat(qualifiedQty).toFixed(1) <= 0) {
        $.messager.alert('提示', '良品数量必须输入!', 'warning');
        $('#barcode_form').find('input[textboxname="qualifiedQty"]').textbox('textbox').focus();
        return;
    }

    // 2021年7月15日 09:31:14 chanchaw 追加检测打印数量必须大于0
    if (!printQty || parseFloat(printQty).toFixed(1) <= 0) {
        $.messager.alert('提示', '打印张数必须输入!', 'warning');
        $('#barcode_form').find('input[textboxname="printQty"]').textbox('textbox').focus();
        return;
    }
    if (fitQty < qualifiedQty) {
        $.messager.alert('提示', '良品数不可大于贴合数！', 'warning');
        return;
    }

    // 检测数量是否匹配：贴合数 = 良品数 + 不良数量
    if( !isAmountMate() ){
        $.messager.alert('提示', '请保证 【 良品数量 + 不良数量 = 贴合数量 】 ！', 'warning');
        return;
    }

    // 次品原因
    let postdata = {
        id: id,
        fitQty: fitQty,
        qualifiedQty: qualifiedQty,
        printQty: printQty,
        flaw0101: convert2Float($('#flaw0101').textbox('getValue')),
        flaw0201: convert2Float($('#flaw0201').textbox('getValue')),
        flaw0202: convert2Float($('#flaw0202').textbox('getValue')),
        flaw0301: convert2Float($('#flaw0301').textbox('getValue')),
        flaw0302: convert2Float($('#flaw0302').textbox('getValue')),
        flaw0401: convert2Float($('#flaw0401').textbox('getValue')),
        flaw0402: convert2Float($('#flaw0402').textbox('getValue')),
        flaw0501: convert2Float($('#flaw0501').textbox('getValue')),
        flaw0502: convert2Float($('#flaw0502').textbox('getValue')),

        flaw0601: convert2Float($('#flaw0601').textbox('getValue')),
        flaw0602: convert2Float($('#flaw0602').textbox('getValue')),
        flaw0603: convert2Float($('#flaw0603').textbox('getValue')),
        flaw0604: convert2Float($('#flaw0604').textbox('getValue')),
        flaw0605: convert2Float($('#flaw0605').textbox('getValue')),
        flaw0606: convert2Float($('#flaw0606').textbox('getValue')),

        flaw0701: convert2Float($('#flaw0701').textbox('getValue')),
        flaw0702: convert2Float($('#flaw0702').textbox('getValue')),

        flaw0801: convert2Float($('#flaw0801').textbox('getValue')),
        flaw0802: convert2Float($('#flaw0802').textbox('getValue')),

        flaw0901: convert2Float($('#flaw0901').textbox('getValue')),
        flaw0902: convert2Float($('#flaw0902').textbox('getValue')),
        flaw0903: convert2Float($('#flaw0903').textbox('getValue')),

        flaw1001: convert2Float($('#flaw1001').textbox('getValue')),
        flaw1101: convert2Float($('#flaw1101').textbox('getValue')),

        flaw1201: convert2Float($('#flaw1201').textbox('getValue')),
        flaw1202: convert2Float($('#flaw1202').textbox('getValue')),
        flaw1203: convert2Float($('#flaw1203').textbox('getValue')),
        flaw1204: convert2Float($('#flaw1204').textbox('getValue')),
        flaw1205: convert2Float($('#flaw1205').textbox('getValue')),
        flaw1301: convert2Float($('#flaw1301').textbox('getValue'))
    };
    let productCoded = $('#barcode_form').serializeObject()['productCoded'];
    let tinyTagId = '';
    let productFileLinked = null;

    // 执行后端请求时锁定前端页面
    $.messager.progress({title: '提示', text: '请稍候...', interval: 5000});
    $.ajax({ // 根据存货编码查询获取表 ProductFile 的一行数据
        url: 'productFile/queryMessageByPfCode/' + productCoded,
        dataType: 'json',
        type: 'GET'
    }).then(function(data){
        // 检测累计良品率是否超过合法的浮动率
        //return checkFloatPercentage(data,postdata);
        productFileLinked = data;// ProductFile对象
        refreshApi(selected);// 刷新api
        // 检测本次良品数量累加之前的良品数向上浮动率是否合法
        return checkFloatPercentage01(data,postdata);
    },()=>{
        $.messager.progress('close');
        $.messager.alert('提示', '检查良品数量浮动率时出现异常！', 'error');
    }).then(preDataRes => {
        return new Promise((resolve,reject)=>{
            const ret = {success:true,message:'没有设置提示文案',data:productFileLinked};
            if(!preDataRes.success){
                $.messager.alert('提示', preDataRes.message, 'error');
                ret.success = false;
                reject();
            }

            // 请求来数据模型：
            // BigDecimal planQty;// 计划数量
            // BigDecimal qualifiedQty;// 累计良品数量
            // Integer floatPercentage;// 上浮百分比，5则表示上浮5%之内都是合法的
            // Integer promptGrade;// 提示等级，0不提示，1仅提示，2强制不可保存
            const preData = preDataRes.data;
            const promptGrade = preDataRes.data.promptGrade;
            if(promptGrade === 0)// 不需要提示则直接退出
                resolve(ret);


            // 累计良品数量没有超过计划数量则不需要验证直接返回
            const planQty = preData.planQty || 0;
            const qualifiedQty = preData.qualifiedQty || 0;
            const diff = qualifiedQty - planQty;
            if(diff<=0)
                resolve(ret);

            const floatPercentageChecked = diff / (planQty === 0 ? 1 : planQty) * 100;
            if(floatPercentageChecked > preData.floatPercentage){// 超过浮动率
                const tip0 = `计划数量${planQty}，累计入库良品数量${qualifiedQty} \n 标准浮动率${preData.floatPercentage}，实际浮动率${floatPercentageChecked}`;
                const tip1 = `${tip0} \n 不可入库！`;
                const tip2 = `${tip0} \n 是否仍然入库？`;
                if(promptGrade == 2){// 强制不允许保存
                    $.messager.alert('提示', tip1, 'error');
                    reject();
                }else {
                    $.messager.confirm('提示', tip2, r => {
                        if (r) resolve(ret);
                        else reject();
                    })
                }
            }else{
                resolve(ret);
            }
        }, ()=>{
            $.messager.progress('close');
            $.messager.alert('提示', '检查良品数量浮动率时出现异常！', 'error');
        });
    }).then(function (res) {
        console.log(res);
        const data = productFileLinked;// res.data = productFile

        if (data != undefined) {
            // 存货档案中设置了强制扫码，则要检测扫描二维码是否通过
            if( !cheat4ScanCode() ){
                if (data['canScanCode']) {
                    if (!$('#barcode_form').form('validate')) {
                        $.messager.progress('close');
                        $.messager.alert('提示', '校验失败!禁止保存!', 'error');
                        return;
                    }
                }
            }
            else{
                // console.log('从响应来的数据中判断canScanCode时进入 else 分支：',data['canScanCode']);
            }

            tinyTagId = data['tinyTagId'] || '';
            refreshApi(selected)// 刷新API
            return $.ajax({ // sales_plan_report 表中修改工程名称 - 生产日报表主表
                // url: 'execPlanMain/updateProjectName',
                url: urlDialogUpdateProjectName,
                data: {
                    id: selected.parentId,
                    projectName: projectName,
                    registerEmployeeId: registerEmployeeId || null
                },
                type: 'POST',
                dataType: 'json'
            });
        }
    }, () => {
        $.messager.progress('close');
        // $.messager.alert('提示', '服务器连接失败!', 'error');
        // $.messager.alert('提示', '检查良品数量浮动率时出现异常1！', 'error');
        console.log('检查良品数量浮动率时出现异常1');
    }).then(data => {
        if (data.success) {
            /**
             * 2021年7月31日 12:19:36 chanchaw
             * 修改 生产计划明细数据，在此之前是覆盖写入数量，请求URL是：salesPlanReportDtl/updateSelective
             * 制作 “执行计划” 之前的累计数量的请求是： salesPlanReportDtl/updateAccumulate
             * 本次修改为将数量累计后写入，请求URL是：execPlanDetail/updateAccumulate
             */
            return $.ajax({
                // url: 'execPlanDetail/updateAccumulate',
                url: urlDialogSave,
                data: postdata,
                type: 'POST',
                dataType: 'json'
            });
        } else {
            $.messager.progress('close');
            $.messager.alert('提示', data.message, 'warning');
        }
    }, () => {
        $.messager.progress('close');
        $.messager.alert('提示', '服务器连接失败!', 'error');
    }).then(function (data) {
        if (data.success) {
            $.messager.show({title: '提示', msg: data.message});
            let printParam = [];

            // 2023年2月15日 新增“执行计划”，在“未完工”标签页的表格中会同时存在
            // “生产计划”和“执行计划”的数据，在原基础上新增两个参数：detailId，execPlan
            getSelectedRow4Print();
            for (let i = 0; i < printQty; i++) {
                printParam.push({
                    reportlet: formData['tagPath'],
                    id: id,
                    detailId: id,
                    execPlan: selectedRow4print.execPlan
                })
            }
            loadForm($('#machineCode').combobox('getValue'));
            if (tinyTagId) {
                $.ajax({
                    url: 'tagLibrary/queryByPk/' + tinyTagId,
                    dataType: 'json', type: 'GET',
                    async: false
                }).then(function (record) {
                    // 2021年10月8日 13:44:59 chanchaw 追加下面代码块为 TOTO 制作的产品用小标签
                    // 要求传入生产计划明细数据主键，而之前做的小标签要求传入存货编码
                    // let rptParam = {};
                    // const tagPath = record['tagPath'];
                    // if( tinyTagParamMode(tagPath) === 1 ){
                    //     rptParam = {reportlet: tagPath, id: id}
                    // }else{
                    //     rptParam = {reportlet: tagPath, pfCoded: productCoded}
                    // }
                    // 2021年10月11日 09:31:58 注释上面代码，提取为一个 function ，模态窗的两个按钮都要用到该逻辑
                    const tagPath = record['tagPath'];
                    const category = record['category'];
                    const rptParam = getRptParam(tagPath,id,productCoded,category,selectedRow4print.execPlan);
                    printParam.push(rptParam);

                    // 2021年10月8日 10:19:00 注释下面代码使用上面的逻辑
                    // 为TOTO制作了产品小标签，传入的参数和之前做的小标签不同
                    // printParam.push({
                    //     reportlet: record['tagPath'],
                    //     pfCoded: productCoded
                    // })
                })
            }
            printFn(printParam);
            if (afterPrinting != undefined) {
                afterPrinting();
            }

        } else {
            $.messager.alert('提示', data.message || data.responseCode, 'warning');
        }
        // 上面的 if 语句的请求采用了同步的方式，
        // 所以可以将解除锁定的代码放在顺序执行的后面
        $.messager.progress('close');
    })
}

//  打印现品票
function printFn(param) {
    function print(param) {
        FR.doURLPDFPrint({
            url: $('body').data('report_url'),
            isPopUp: false,
            data: {
                reportlets: param
            }
        })
    }
    // param.detailId = 49;
    // param.execPlan = 1;

    if (window.top != window.self) {
        print(param);
        return;
    }
    if ('undefined' == typeof FR) {
        $.getScript($('body').data('report_url') + '?op=emb&resource=finereport.js', function () {
            print(param);
        });
    } else {
        print(param)
    }
}

//  导出
function btn_export() {
    switch (getSelectedIndex()) {
        case 0:
            exportExcel('#e_grid', '未完工生产计划登记');
            break;
        case 1:
            $('#e_grid_finished').data('kendoGrid').saveAsExcel();
            break;
    }
}

//  二维码日报 - 模态窗
function btn_barcode() {
    let selected = $('#e_grid').datagrid('getSelected');
    let projectName = $('#projectName').combobox('getValue');
    let registerEmployeeId = $('#registerEmployeeId').combobox('getValue');
    if (selected == undefined) {
        $.messager.alert('提示', '选中行再使用本功能！', 'warning');
        return;
    }
    if (!projectName) {
        $.messager.alert('提示', '选择工程后再执行本操作！', 'warning');
        return;
    }
    let div = `<div class="easyui-dialog" id="barcode_dialog" >
                <form style="width: 100%;height: 100%;" id="barcode_form">
                    <div class="easyui-layout" data-options="fit:true">

                        <!-- 左边现品票 -->
                        <div data-options="region:'west',split:false" title="现品票" style="width:600px;">

                            <div data-options="region:'north',height:'auto'">
                                <div class="input-group">
                                    <input name="id" type="hidden">
                                    <input class="easyui-textbox" id="productCoded" name="productCoded" data-options="label:'存货编码：', labelAlign:'right', readonly:true,">
                                    <input class="easyui-textbox" name="productName" data-options="label:'存货名称：',labelAlign:'right',editable:false">
                                    
                                </div>

                                <div class="input-group">
                                    <!-- width:697, -->
                                    <input class="easyui-textbox" name="specification" data-options="label:'规格型号：',labelAlign:'right',editable:false">
                                    <input class="easyui-textbox" name="printingDieCut" data-options="label:'印刷模切：',labelAlign:'right',editable:false">
                                </div>
                                <div class="input-group"><input class="easyui-numberbox" name="planQty" data-options="label:'计划数量：',labelAlign:'right',editable:false,width:461"></div>
                                <div class="input-group">
                                    <input controlled class="easyui-textbox" prompt="原票信息" name="ticketData" id="ticketData" data-options="type:'password',label:'<span style=&quot;color:red;&quot;>*</span>原票信息：',labelAlign:'right',editable:true,width:461,required:true,validType:'ticketDataValidate[&quot;#productCoded&quot;]',onChange:textboxTicketChange">
                                    <input name="colorBlock0" class="easyui-textbox" data-options="width:36,readonly:true,onChange:textboxColorChange"> 
                                </div>
                                
                                <div id="printTemplate1Div" class="input-group">
                                    <input controlled id="printTemplate1" class="easyui-textbox" name="printTemplate1" data-options="type:'password',label:'印版1：',labelAlign:'right',width:461,validType:'printTemplateA'," />
                                    <input name="colorBlock1" class="easyui-textbox" data-options="width:36,readonly:true,onChange:textboxColorChange" /></div>
                                
                                <div id="printTemplate2Div" class="input-group">
                                    <input controlled id="printTemplate2" class="easyui-textbox" name="printTemplate2" data-options="type:'password',label:'印版2：',labelAlign:'right',width:461,validType:'printTemplateB'," />
                                    <input name="colorBlock2" class="easyui-textbox" data-options="width:36,readonly:true,onChange:textboxColorChange" /></div>
                                
                                <div id="printTemplate3Div" class="input-group">
                                    <input controlled id="printTemplate3" class="easyui-textbox" name="printTemplate3" data-options="type:'password',label:'印版3：',labelAlign:'right',width:461,validType:'printTemplateC'," />
                                    <input name="colorBlock3" class="easyui-textbox" data-options="width:36,readonly:true,onChange:textboxColorChange" /></div>
                                    
                                <div id="dieCutDiv" class="input-group">
                                    <input controlled id="dieCut" class="easyui-textbox" name="dieCut" data-options="type:'password',label:'刀模：',labelAlign:'right',width:461,validType:'printTemplateD'," />
                                    <input name="colorBlock4" class="easyui-textbox" data-options="width:36,readonly:true,onChange:textboxColorChange" /></div>
                                    
                                <div id="productBarcodeDiv" class="input-group">
                                    <input controlled id="productBarcode" class="easyui-textbox" name="productBarcode" data-options="type:'password',label:'条码：',labelAlign:'right',width:461,validType:'productBarcode'," />
                                    <input name="colorBlockBarcode" class="easyui-textbox" data-options="width:36,readonly:true,onChange:textboxColorChange" /></div>
                            </div>

                            <div data-options="region:'center'">
                                <div class="input-group">
                                    <input id="fitQty" name="fitQty" class="easyui-numberbox" data-options="label:'贴合数量：',labelAlign:'right',min:1">
                                    <input name="printQty" class="easyui-numberbox" data-options="label:'打印张数：',labelAlign:'right',min:1">
                                </div>
                                <div class="input-group">
                                    <input id="qualifiedQty" name="qualifiedQty" class="easyui-numberbox" data-options="label:'良品数量：',labelAlign:'right',min:1">
                                    <input name="printColorBlocks" class="easyui-textbox" 
                                        data-options="width:120,readonly:true,label:'纸张颜色：',labelAlign:'right',onChange:function(newVal,oldVal){
                                            if(newVal){ $(this).textbox('textbox').css({color:newVal,backgroundColor:newVal}); } 
                                            else { $(this).textbox('textbox').css({color:'white',backgroundColor:'white'}) }
                                        }">
                                    <input type="hidden" name="tagPath">
                                </div>

                                <div class="input-group">
                                        <!-- width:464, -->
                                    <input id="badQty" name="badQty" class="easyui-numberbox" data-options="label:'不良数量：',labelAlign:'right'">
                                    <input name="printPrompt" class="easyui-textbox" data-options="readonly:true,label:'打印提示：',labelAlign:'right'">
                                </div>
                            </div>
                        </div> <!-- 左边现品票结束 -->


                        <!-- 不良原因 - 中间 -->
                        <div data-options="region:'center',split:false" title="不良原因1">
                            <table id="tab1">
                                <tr><td><input id="flaw0101" class="easyui-textbox" label="1. 开机调试:" labelPosition="left" style="width:100%;"></td></tr>
                            
                                <tr><td><label>2. 纸板卡破：</label></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw0201" class="easyui-textbox sub-flaw" label="A. 设定异常:" labelPosition="left" style="width:100%;"></div></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw0202" class="easyui-textbox sub-flaw" label="B. 纸板弯翘:" labelPosition="left" style="width:100%;"></div></td></tr>

                                <tr><td><label>3. 印刷跑位：</label></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw0301" class="easyui-textbox sub-flaw" label="A. 设定异常:" labelPosition="left" style="width:100%;"></div></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw0302" class="easyui-textbox sub-flaw" label="B. 纸板弯翘:" labelPosition="left" style="width:100%;"></div></td></tr>
                                
                                <tr><td><label>4. 模切跑位：</label></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw0401" class="easyui-textbox sub-flaw" label="A. 设定异常:" labelPosition="left" style="width:100%;"></div></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw0402" class="easyui-textbox sub-flaw" label="B. 纸板弯翘:" labelPosition="left" style="width:100%;"></div></td></tr>

                                <tr><td><label>5. 开槽跑位：</label></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw0501" class="easyui-textbox sub-flaw" label="A. 设定异常:" labelPosition="left" style="width:100%;"></div></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw0502" class="easyui-textbox sub-flaw" label="B. 纸板弯翘:" labelPosition="left" style="width:100%;"></div></td></tr>

                                <tr><td><label>6. 印刷不良：</label></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw0601" class="easyui-textbox sub-flaw" label="A. 色差:" labelPosition="left" style="width:100%;"></div></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw0602" class="easyui-textbox sub-flaw" label="B. 印刷不匀:" labelPosition="left" style="width:100%;"></div></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw0603" class="easyui-textbox sub-flaw" label="C. 印刷露底:" labelPosition="left" style="width:100%;"></div></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw0604" class="easyui-textbox sub-flaw" label="D. 印版开胶:" labelPosition="left" style="width:100%;"></div></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw0605" class="easyui-textbox sub-flaw" label="E. 缺失、重影:" labelPosition="left" style="width:100%;"></div></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw0606" class="easyui-textbox sub-flaw" label="F. 批次错误:" labelPosition="left" style="width:100%;"></div></td></tr>
                            </table>
                        </div>

                        <!-- 不良原因 - 右边 -->
                        <div data-options="region:'east',split:false" title="不良原因2" style="width:300px;">
                            <table id="tab2">
                                <tr><td><label>7. 压线跑位：</label></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw0701" class="easyui-textbox sub-flaw" label="A. 设定异常:" labelPosition="left" style="width:100%;"></div></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw0702" class="easyui-textbox sub-flaw" label="B. 纸板弯翘:" labelPosition="left" style="width:100%;"></div></td></tr>

                                <tr><td><label>8. 线板爆线：</label></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw0801" class="easyui-textbox sub-flaw" label="A. 面纸爆线:" labelPosition="left" style="width:100%;"></div></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw0802" class="easyui-textbox sub-flaw" label="B. 底纸爆线:" labelPosition="left" style="width:100%;"></div></td></tr>

                                <tr><td><label>9. 纸板脏污：</label></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw0901" class="easyui-textbox sub-flaw" label="A. 面纸脏污:" labelPosition="left" style="width:100%;"></div></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw0902" class="easyui-textbox sub-flaw" label="B. 底纸脏污:" labelPosition="left" style="width:100%;"></div></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw0903" class="easyui-textbox sub-flaw" label="C. 接头纸:" labelPosition="left" style="width:100%;"></div></td></tr>

                                <tr><td><input id="flaw1001" class="easyui-textbox" label="10. 反投料:" labelPosition="left" style="width:100%;"></td></tr>

                                <tr><td><input id="flaw1101" class="easyui-textbox" label="11. 打包破损:" labelPosition="left" style="width:100%;"></td></tr>

                                <tr><td><label>12. 粘合不良：</label></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw1201" class="easyui-textbox sub-flaw" label="A. 粘箱错位:" labelPosition="left" style="width:100%;"></div></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw1202" class="easyui-textbox sub-flaw" label="B. 内黏连:" labelPosition="left" style="width:100%;"></div></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw1203" class="easyui-textbox sub-flaw" label="C. 胶外溢:" labelPosition="left" style="width:100%;"></div></td></tr>
                                <tr><td><div class="subFlawContainer">
                                    <input id="flaw1204" class="easyui-textbox sub-flaw" label="D. 开胶:" labelPosition="left" style="width:100%;"></div></td></tr>
                                <tr><td><div class="subFlawContainer"><input id="flaw1205" class="easyui-textbox sub-flaw" label="E. 粘合异物混入:" labelPosition="left" style="width:100%;"></div></td></tr>

                                <tr><td><input id="flaw1301" class="easyui-textbox" label="13. 其他:" labelPosition="left" style="width:100%;"></td></tr>
                            </table>
                        </div>
                        



                    </div>
                </form>
               </div>`;

    if ($('#barcode_dialog').length <= 0) {
        $(div).appendTo($('body'));

        // 监听不良原因内容的变化
        flawInputChangeHandler();

        $('#barcode_dialog').dialog({
            title: '日报',
            iconCls: 'icon-script_code_red',
            width: 1250,
            height: 630,
            modal: true,
            closed: false,
            resizable: true,
            onOpen: function () {// 模态窗打开时进行一系列初始化动作
                //  渲染表单
                // 根据选中的行是否执行计划及时刷新请求 url
                refreshApi(selected);
                $.parser.parse($('#barcode_dialog'));
                let currentDialog = $(this);
                $.messager.progress({
                    title: '',
                    msg: '请稍等...',
                    interval: 5000
                });
                new Promise(function (resolve, reject) {
                    $.ajax({
                        // url: 'execPlanDetail/queryByPk/' + selected.id,
                        url: urlDialogInit,
                        dataType: 'json',
                        success: function (data) {
                            resolve(data)
                        },
                        error: function () {
                            reject('出现错误！')
                        }
                    })
                })
                    .then(function (data) {
                        if (data) {
                            $('#barcode_form').form('load', {
                                productCoded: data['productCode'],
                                planQty: data['planQty'] || 0
                            });
                            $('#barcode_form').find('input[name="ticketData"]').parent().find('input').eq(0).focus();
                            return $.ajax({url: 'productFile/queryByPfCoded/' + data['productCode'], data: {}});
                        } else {
                            $.messager.alert('提示', '数据查询失败!', 'warning');
                            currentDialog.dialog('destroy');
                        }
                    })
                    .then(function (data) {
                        if (data) {
                            productFile = data;// 将请求来的存货档案缓存起来
                            $('#barcode_form').form('load', {
                                productName: data['pfName'],
                                specification: data['pfSpecification'],
                                printPrompt: data['printPrompt'],
                                printColorBlocks: data['printColorBlocks'],
                                printQty: 1,
                                id: selected.id
                            });
                            let ajax = [];
                            if (data['tagId'])
                                ajax.push($.ajax({
                                    url: 'tagLibrary/queryByPk/' + data['tagId'],
                                    dataType: 'json', type: 'GET'
                                }));
                            let projectName = $('#projectName').combobox('getValue');
                            if (projectName) {
                                let getData = $('#projectName').combobox('getData') || [];
                                let opts = $('#projectName').combobox('options');
                                let projectId = '';
                                for (let i of getData) {
                                    if (projectName == i[opts['valueField']]) {
                                        projectId = i['id'];
                                        break;
                                    }
                                }
                                ajax.push($.ajax({
                                    url: 'tagLibrary/listQuery',
                                    data: {tagProjectId: projectId},
                                    dataType: 'json', type: 'GET'
                                }));
                            }
                            return Promise.all(ajax);
                        }
                    })
                    .then(data => {
                        let tagPath = '';
                        if (data instanceof Array && data.length == 1) {
                            if (data[0] instanceof Array && data[0].length > 0) {
                                tagPath = data[0][0]['tagPath'];
                            } else {
                                tagPath = data[0]['tagPath'];
                            }
                        } else if (data instanceof Array && data.length == 2) {
                            if (data[0]['tagPath']) {
                                tagPath = data[0]['tagPath'];
                            } else if (data[1].length > 0) {
                                tagPath = data[1][0]['tagPath'];
                            } else {
                                tagPath = data[0]['tagPath'];
                            }
                        }
                        if (tagPath) {
                            $('#barcode_form').form('load', {
                                tagPath: tagPath
                            });
                        } else {
                            $.messager.alert('提示', '未设置标签！', 'error');
                        }
                    })
                    .finally(function () {
                        $.messager.progress('close');
                    })
            },
            onClose: function () {
                //  关闭并销毁
                $(this).dialog('destroy');
            },
            buttons: [ // 模态窗按钮执行逻辑
                {
                    text: '打印', iconCls: 'icon-print', handler: e => {
                        justPrint();
                    }
                },
                {
                    text: '保存', iconCls: 'icon-save', handler: e => {
                        saveAndPrint(projectName, registerEmployeeId, selected, () => {
                            $('#barcode_dialog').dialog('destroy');
                        });
                    }
                }]
        })
    }
}

//  关联入库
function btn_related() {
    let selected;
    switch (getSelectedIndex()) {
        case 0:
            selected = $('#e_grid').datagrid('getSelected')
            break;
        case 1:
            let kGrid = $('#e_grid_finished').data('kendoGrid');
            selected = kGrid.dataItem(kGrid.select());
            break;
    }
    if (selected == undefined) {
        $.messager.alert('提示', '未选中！', 'warning');
        return;
    }
    $.messager.confirm('提示', selected.productCode + '是否关联入库？', r => {
        if (r) {
            $.post('productOrderBill/linkInsert', {id: selected.id}, data => {
                if (data['id']) {
                    $.messager.show({
                        title: '提示',
                        msg: `关联入库成品单据编号:${data['orderCode']}<br>
                              关联入库存货编码:${data['detail'][0]['productCoded']}<br>
                              关联入库数量:${data['detail'][0]['amount'] || 0}`
                    })
                } else {
                    $.messager.alert('提示', data['message'] || '未知错误！', 'error');
                }
            }, 'json');
        }
    })
}

//  打印现品票 - 只有在第二个标签页 “已完工” 页面上本按钮可用
function btn_print_ticket() {
    // 检测工程名称失败则退出
    // 机台号有默认所以不会空白，不用检测
    if( !checkProjectName() ) return;

    let selected;
    switch (getSelectedIndex()) {
        case 0:
            selected = $('#e_grid').datagrid('getSelected');
            break;
        case 1:
            let kGrid = $('#e_grid_finished').data('kendoGrid');
            selected = kGrid.dataItem(kGrid.select());
            break;
    }
    if (selected == undefined) {
        $.messager.alert('提示', '未选中！', 'warning');
        return;
    }
    let printPrompt = '';
    $.ajax({
        url: 'productFile/queryByPfCoded/' + selected['productCode'],
        type: 'GET',
        dataType: 'json',
    }).then(data => {
        if (!data) {
            $.messager.alert('提示', '存货编码不存在!', 'warning');
            return;
        }
        printPrompt = data['printPrompt'] ? `<br/><span style="padding:1px;width:12px;height:12px;display:inline-block;color: ${data['printColorBlocks'] || 'white'};background-color:  ${data['printColorBlocks'] || 'white'}"></span>${data['printPrompt']}` : ``;
        let ajax = [];
        if (data['tagId'])
            ajax.push($.ajax({
                url: 'tagLibrary/queryByPk/' + data['tagId'],
                dataType: 'json', type: 'GET'
            }));
        let projectName = $('#projectName').combobox('getValue');
        if (projectName) {
            let getData = $('#projectName').combobox('getData') || [];
            let opts = $('#projectName').combobox('options');
            let projectId = '';
            for (let i of getData) {
                if (projectName == i[opts['valueField']]) {
                    projectId = i['id'];
                    break;
                }
            }
            ajax.push($.ajax({
                url: 'tagLibrary/listQuery',
                data: {tagProjectId: projectId},
                dataType: 'json', type: 'GET'
            }));
        }
        return Promise.all(ajax).then(function (primiseData) {
            let tagPath = '';
            if (primiseData instanceof Array && primiseData.length == 1) {
                if (primiseData[0] instanceof Array && primiseData[0].length > 0) {
                    tagPath = primiseData[0][0]['tagPath'];
                } else {
                    tagPath = primiseData[0]['tagPath'];
                }
            } else if (primiseData instanceof Array && primiseData.length == 2) {
                if (primiseData[0]['tagPath']) {
                    tagPath = primiseData[0]['tagPath'];
                } else if (primiseData[1].length > 0) {
                    tagPath = primiseData[1][0]['tagPath'];
                } else {
                    tagPath = primiseData[0]['tagPath'];
                }
            }
            if (!tagPath) {
                $.messager.alert('提示', selected['productCode'] + ' 未设置标签样式!', 'warning');
                return;
            }

            // 已完成 标签页中“打印现品票”按钮的弹出模态窗
            let formData = [{
                title: '打印张数',
                field: 'count',
                editor: {type: 'numberbox', options: {min: 1, value: 1, required: true}}
            },
            {
                title: '生产日期',
                field: 'productDate',
                editor: {type: 'datebox', options: {value: getCurrentDate(0)}}
            },];
            $.formDialog.open({
                columns: formData,
                width: 303,
                height: 157,
                mode: '打印提示',
                iconCls: 'icon-print',
                buttons: [{
                    text: '取消',
                    iconCls: 'icon-cancel', handler: function (e) {
                        $.formDialog.close();
                    }
                },
                {
                    text: '打印',
                    iconCls: 'icon-print',
                    handler: function (e) {
                        let param = $('.form-dialog-edit').find('form').serializeObject();
                        let r = param['count'] || 1;
                        if (!$('.form-dialog-edit').find('form').form('validate')) return;
                        try {
                            let printParam = [];
                            for (let i = 0; i < r; i++) {
                                // oneRpt = getRptParam(tagPath, selected.id, selected['productCode']);
                                // console.log('现品票打印参数是：', oneRpt);
                                // printParam.push(oneRpt);
                                // “打印现品票”按钮会及时获取选中行，这里不需调用getSelectedRow4Print，直接使用selected
                                printParam.push({
                                    reportlet: tagPath,
                                    id: selected.id,
                                    date: param['productDate'] || '',
                                    detailId: selected.id,
                                    execPlan: selected.execPlan
                                })
                                // console.log('2385打印现品票的参数依次是：',tagPath,selected.id);
                            }
                            if (data['tinyTagId']) {
                                $.ajax({
                                    url: 'tagLibrary/queryByPk/' + data['tinyTagId'],
                                    dataType: 'json', type: 'GET',
                                    async: false
                                }).then(function (record) {
                                    // 获取选中行数据构建打印报表需要的参数
                                    const tagPath1 = record['tagPath'] || '';
                                    const planDetailId1 = selected['id'];
                                    const productCoded1 = selected['productCode'];
                                    const category = record['category'];
                                    const rptParam = getRptParam(tagPath1, planDetailId1, productCoded1,category,selected.execPlan);
                                    rptParam.date = param['productDate'];
                                    // console.log('2385打印小标签封装的参数是：',rptParam);

                                    // 2023年2月15日制作执行计划修改 “中外制药 10枚标签” 数据源为存储过程时
                                    // 追加的字段
                                    rptParam.productDate = param['productDate'];

                                    printParam.push(rptParam);
                                    // printParam.push({
                                    //     reportlet: record['tagPath'] || '',
                                    //     pfCoded: selected['productCode']
                                    // })
                                })
                            }
                            printFn(printParam);
                            // $.post('execPlanDetail/updateSelective', {
                            $.post(urlGridFinishedPrintUpdate, {
                                id: selected.id,
                                printQty: r
                            }, function (data) {
                                $.formDialog.close();
                            }, 'json');
                        } catch (e) {
                            console.table(e);
                            $.messager.alert('提示', '打印出错！', 'error');
                        }
                    }
                }]
            });


        })
    }, () => {
        $.messager.alert('提示', '连接服务器失败!', 'error');
    })
}

function textboxColorChange(newVal, oldVal) {
    if (newVal) {
        $(this).textbox('textbox').css({backgroundColor: newVal, color: newVal});
    }
}

// 原票信息 文本框变动触发的事件
function textboxTicketChange(newVal, oldVal) {
    if (newVal) {
        let count = (newVal.substring(18, 27) == '1-00-0000' ? 0 : 1)
            + (newVal.substring(38, 47) == '3-00-0000' ? 0 : 1)
            + (newVal.substring(28, 37) == '2-00-0000' ? 0 : 1);
        let dieCount = newVal.substring(48, 57) == '4-00-000' ? 0 : 1;
        let prefix = '';
        if (count == 1) {
            prefix = '单色印刷';
        } else if (count == 2) {
            prefix = '双色印刷';
        } else if (count == 3) {
            prefix = '三色印刷';
        }
        let suffix = dieCount > 0 ? '模切' : '';
        let name = '';
        if (count > 0 && dieCount > 0) {
            name = prefix + '加' + suffix;
        } else {
            name = prefix + suffix;
        }
        $('#barcode_form').form('load', {
            printingDieCut: name,
            printTemplate1: '',
            printTemplate2: '',
            printTemplate3: '',
            dieCut: '',
            productBarcode: '',
            fitQty: ''
        });
        if ($(this).textbox('validate')) {
            let check1 = newVal.substring(18, 27) == '1-00-0000';
            let check2 = newVal.substring(28, 37) == '2-00-0000';
            let check3 = newVal.substring(38, 47) == '3-00-0000';
            let check4 = newVal.substring(48, 57) == '4-00-000';
            let needCheckBarcode = productFile.pfRememberCode3 ? true : false;

            if(needCheckBarcode){
                // 存货档案中字段“商品条码”有内容则需要验证，相反则不需要验证
                $('#productBarcode').validatebox({
                    required: true,
                    validType: 'productBarcode'
                });
            }else {
                $('#productBarcode').validatebox({
                    required: false
                });
            }

            if( !check1 ) {
                // console.log('要素一，验证');
                $('#printTemplate1').validatebox({
                    required: true,
                    validType: 'printTemplateA'
                });
            }else{
                // console.log('要素一，不验证');
                $('#printTemplate1').validatebox({
                    required: false
                });
            }

            if( !check2 ) {
                // console.log('要素二，验证');
                $('#printTemplate2').validatebox({
                    required: true,
                    validType: 'printTemplateB'
                });
            }else{
                // console.log('要素二，不验证');
                $('#printTemplate2').validatebox({
                    required: false
                });
            }

            if( !check3 ) {
                // console.log('要素三，验证');
                $('#printTemplate3').validatebox({
                    required: true,
                    validType: 'printTemplateC'
                });
            }else{
                // console.log('要素三，不验证');
                $('#printTemplate3').validatebox({
                    required: false
                });
            }

            if( !check4 ) {
                // console.log('要素四，验证');
                $('#dieCut').validatebox({
                    required: true,
                    validType: 'printTemplateD'
                });
            }else{
                // console.log('要素四，不验证');
                $('#dieCut').validatebox({
                    required: false
                });
            }


            $('#printTemplate1Div').css({display: check1 ? 'none' : 'block'});
            $('#printTemplate2Div').css({display: check2 ? 'none' : 'block'});
            $('#printTemplate3Div').css({display: check3 ? 'none' : 'block'});
            $('#dieCutDiv').css({display: check4 ? 'none' : 'block'});
            $('#productBarcodeDiv').css({display: needCheckBarcode ? 'block':'none'});

            //if( check3 ) $('#printTemplate3Div').remove();

        }
    } else {
        $('#barcode_form').form('load', {
            printingDieCut: '',
            printTemplate1: '',
            printTemplate2: '',
            printTemplate3: '',
            dieCut: '',
        });
        $('#printTemplate1Div').css({display: 'block'});
        $('#printTemplate2Div').css({display: 'block'});
        $('#printTemplate3Div').css({display: 'block'});
        $('#dieCutDiv').css({display: 'block'});
        $('#productBarcodeDiv').css({display: 'block'});

        // console.log('统一设置为不验证');
        $('#printTemplate1Div').validatebox({ required: false });
        $('#printTemplate2Div').validatebox({ required: false });
        $('#printTemplate3Div').validatebox({ required: false });
        $('#dieCutDiv').validatebox({ required: false });
        $('#productBarcodeDiv').validatebox({ required: false });
    }
}

//  关闭
function btn_close() {
    if (getState() == undefined || getState() == 0) {
        $.messager.confirm('确认', '是否关闭页面,单据尚未保存', function (r) {
            if (r) {
                closeTab();
            }
        })
    } else {
        closeTab();
    }

    function closeTab() {
        if (window.top == window.self) {
            //  退出登录
            $.ajax({
                url: 'system/logout',
                type: 'POST',
                dataType: 'json',
                complete: function (xhr, status) {
                    window.localStorage.clear();
                    window.location.reload();
                }
            })
        } else {
            window.parent.closeTab();
        }
    }
}

function getSelectedIndex() {
    let tab = $('#tabs').tabs('getSelected');
    let index = $('#tabs').tabs('getTabIndex', tab);
    return index;
}

$.extend($.fn.validatebox.defaults.rules, {
    ticketDataValidate: {
        validator: function (value, param) {
            let p = /^[a-zA-Z0-9]{4}-[a-zA-Z0-9]{5}-[\d\D]{4}-[0-9]-[0-9]-[0-9][0-9]-[\d\D]{4}-[0-9]-[0-9][0-9]-[\d\D]{4}-[0-9]-[0-9][0-9]-[\d\D]{4}-[0-9]-[0-9][0-9]-[\d\D]{3}$/i;
            let test = p.test(value);
            let b = test;
            if (param && param.length > 0) {
                let _value = $(param[0]).textbox('getValue');
                b = value.slice(0, _value.length) == _value && test;
            }
            if (b) {
                $('#barcode_form').find('input[textboxname="colorBlock0"]').textbox('setValue', 'green');
            } else {
                $('#barcode_form').find('input[textboxname="colorBlock0"]').textbox('setValue', 'red');
            }
            return b;
        },
        message: '原票信息填写格式错误!'
    },
    printTemplateA: {
        validator: function (value, param) {
            let ticketData = $('#ticketData').textbox('getValue');
            let p = /^[a-zA-Z0-9]{4}-[a-zA-Z0-9]{5}-[\d\D]{4}-[0-9]-[0-9]-[\d\D]{2}-[\d\D]{4}$/i;
            let rightValue = ticketData.substring(0, 18) + ticketData.substring(18, 27);
            if (!value) {
                value = ticketData.splice(0, 16) + '1-00-0000'
            }
            if (p.test(value) && value == rightValue) {
                $('#barcode_form').find('input[textboxname="colorBlock1"]').textbox('setValue', 'green');
            } else {
                $('#barcode_form').find('input[textboxname="colorBlock1"]').textbox('setValue', 'red');
            }
            return p.test(value) && value == rightValue;
        },
        message: '印版1选择错误!'
    },
    printTemplateB: {
        validator: function (value, param) {
            let ticketData = $('#ticketData').textbox('getValue');
            let p = /^[a-zA-Z0-9]{4}-[a-zA-Z0-9]{5}-[\d\D]{4}-[0-9]-[0-9]-[\d\D]{2}-[\d\D]{4}$/i;
            let rightValue = ticketData.substring(0, 18) + ticketData.substring(28, 37);
            if (!value) {
                value = ticketData.splice(0, 16) + '2-00-0000'
            }
            if (p.test(value) && value == rightValue) {
                $('#barcode_form').find('input[textboxname="colorBlock2"]').textbox('setValue', 'green');
            } else {
                $('#barcode_form').find('input[textboxname="colorBlock2"]').textbox('setValue', 'red');
            }
            return p.test(value) && value == rightValue;
        },
        message: '印版2选择错误'
    },
    printTemplateC: {
        validator: function (value, param) {
            let ticketData = $('#ticketData').textbox('getValue');
            let p = /^[a-zA-Z0-9]{4}-[a-zA-Z0-9]{5}-[\d\D]{4}-[0-9]-[0-9]-[\d\D]{2}-[\d\D]{4}$/i;
            let rightValue = ticketData.substring(0, 18) + ticketData.substring(38, 47);
            if (!value) {
                value = ticketData.splice(0, 16) + '3-00-0000'
            }
            if (p.test(value) && value == rightValue) {
                $('#barcode_form').find('input[textboxname="colorBlock3"]').textbox('setValue', 'green');
            } else {
                $('#barcode_form').find('input[textboxname="colorBlock3"]').textbox('setValue', 'red');
            }
            return p.test(value) && value == rightValue;
        },
        message: '印版3选择错误'
    },
    printTemplateD: {
        validator: function (value, param) {
            let ticketData = $('#ticketData').textbox('getValue');
            let p = /^[a-zA-Z0-9]{4}-[a-zA-Z0-9]{5}-[\d\D]{4}-[0-9]-[0-9]-[\d\D]{2}-[\d\D]{3}$/i;
            let rightValue = ticketData.substring(0, 18) + ticketData.substring(48, 57);
            if (!value) {
                value = ticketData.splice(0, 16) + '4-00-000'
            }
            if (p.test(value) && value == rightValue) {
                $('#barcode_form').find('input[textboxname="colorBlock4"]').textbox('setValue', 'green');
            } else {
                $('#barcode_form').find('input[textboxname="colorBlock4"]').textbox('setValue', 'red');
            }
            return p.test(value) && value == rightValue;
        },
        message: '刀模选择错误'
    },
    productBarcode: {// 验证商品条码
        validator: function (value, param) {
            const barCode = productFile.pfRememberCode3 || '';
            const target = value || '';
            const result = target === barCode ? true:false;
            if(result)
                $('#barcode_form').find('input[textboxname="colorBlockBarcode"]').textbox('setValue', 'green');
            else
                $('#barcode_form').find('input[textboxname="colorBlockBarcode"]').textbox('setValue', 'red');
            return result;
        },
        message: '商品条码错误'
    }
})

// 2021年7月15日 09:09:30 下面是 chanchaw 添加的代码
// 保存前进行的数据合法检测，返回 false 表示不可保存
function check4Save() {

    return true;
}

// 不良原因文本输入框内容变动响应事件
function flawInputChangeHandler(){
    $('#flaw0101').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw0201').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw0202').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw0301').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw0302').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw0401').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw0402').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw0501').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw0502').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw0601').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw0602').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw0603').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw0604').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw0605').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw0606').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw0701').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw0702').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw0801').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw0802').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw0901').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw0902').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw0903').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw1001').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw1101').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw1201').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw1202').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw1203').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw1204').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw1205').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })

    $('#flaw1301').textbox({
        onChange: function(newVal,oldVal){
            const newValue = convert2Float(newVal);
            updateBadQty(newValue);
        }
    })
}

// 传入要增加的数量更新不良数量
function updateBadQty(qty){
    const val0 = convert2Float($('#badQty').textbox('getValue'));
    const val0101 = convert2Float($('#flaw0101').textbox('getValue'));
    const val0201 = convert2Float($('#flaw0201').textbox('getValue'));
    const val0202 = convert2Float($('#flaw0202').textbox('getValue'));
    const val0301 = convert2Float($('#flaw0301').textbox('getValue'));
    const val0302 = convert2Float($('#flaw0302').textbox('getValue'));
    const val0401 = convert2Float($('#flaw0401').textbox('getValue'));
    const val0402 = convert2Float($('#flaw0402').textbox('getValue'));
    const val0501 = convert2Float($('#flaw0501').textbox('getValue'));
    const val0502 = convert2Float($('#flaw0502').textbox('getValue'));
    const val0601 = convert2Float($('#flaw0601').textbox('getValue'));
    const val0602 = convert2Float($('#flaw0602').textbox('getValue'));
    const val0603 = convert2Float($('#flaw0603').textbox('getValue'));
    const val0604 = convert2Float($('#flaw0604').textbox('getValue'));
    const val0605 = convert2Float($('#flaw0605').textbox('getValue'));
    const val0606 = convert2Float($('#flaw0606').textbox('getValue'));
    const val0701 = convert2Float($('#flaw0701').textbox('getValue'));
    const val0702 = convert2Float($('#flaw0702').textbox('getValue'));
    const val0801 = convert2Float($('#flaw0801').textbox('getValue'));
    const val0802 = convert2Float($('#flaw0802').textbox('getValue'));
    const val0901 = convert2Float($('#flaw0901').textbox('getValue'));
    const val0902 = convert2Float($('#flaw0902').textbox('getValue'));
    const val0903 = convert2Float($('#flaw0903').textbox('getValue'));
    const val1001 = convert2Float($('#flaw1001').textbox('getValue'));
    const val1101 = convert2Float($('#flaw1101').textbox('getValue'));
    const val1201 = convert2Float($('#flaw1201').textbox('getValue'));
    const val1202 = convert2Float($('#flaw1202').textbox('getValue'));
    const val1203 = convert2Float($('#flaw1203').textbox('getValue'));
    const val1204 = convert2Float($('#flaw1204').textbox('getValue'));
    const val1205 = convert2Float($('#flaw1205').textbox('getValue'));
    const val1301 = convert2Float($('#flaw1301').textbox('getValue'));
    const result = val0101 + val0201 + val0202 + val0301 + val0302 + val0401 + val0402 + val0501 + val0502 + val0601 + val0602 +
        val0603 + val0604 + val0605 + val0606 + val0701 + val0702 + val0801 + val0802 + val0901 + val0902 + val0903 + val1001 + 
        val1101 + val1201 + val1202 + val1203 + val1204 + val1205 + val1301 
    $('#badQty').textbox('setValue',result);
    return result;
}

// 2021年8月1日 22:01:18 chanchaw
// 比较贴合数应该等于良品数 + 不良数量
function isAmountMate(){
    // console.log('下面是从控件获取的结果：');
    // console.log("total:",$('#fitQty').textbox('getValue'));
    // console.log("qualifiedQty:",$('#qualifiedQty').textbox('getValue'));
    // console.log("贴合控件对象：",$('#fitQty'));
    // console.log("良品控件对象：",$('#qualifiedQty'));

    const total = convert2Float($('#fitQty').textbox('getValue'));
    const qualifiedQty = convert2Float($('#qualifiedQty').textbox('getValue'));
    const badQty = convert2Float(updateBadQty());
    const addSum = qualifiedQty + badQty;

    // console.log('下面是转换数据类型之后的结果');
    // console.log($('#badQty'));
    // console.log("total:",total);
    // console.log("qualifiedQty:",qualifiedQty);
    // console.log("badQty:",badQty);
    // console.log("addSum:",addSum);
    const ret = total == addSum ? true : false;
    // console.log("ret:",ret);
    return ret;
}

// 2021年8月6日 11:04:23 chanchaw
// 检测是否选择了工程名，选择了则返回 true 相反返回 false
function checkProjectName(){
    let projectName = $('#projectName').combobox('getValue');
    if( !projectName ){
        $.messager.alert('提示', '选择工程后再执行本操作!', 'warning');
        return false;
    }
    return true;
}


// 修改入库数 弹出的模态窗中填充数据
// selectedData 选中行的第一行
// 给表格上面的：计划数量、贴合数量、良品数量   填充数据
function fillUpdateFitQty(selectedData){
    $('#planQtyUpdate').textbox('setValue',selectedData['planQty']);
    $('#fitQtyUpdate').textbox('setValue',selectedData['fitQty']);
    $('#qualifiedQtyUpdate').textbox('setValue',selectedData['qualifiedQty']);
}

// 2021年8月6日 14:57:42
// 用于修改 贴合数量、良品数量的模态窗
// 本日发现有部分操作导致贴合数量、良品数量翻倍
// 使用本功能调整此类异常数据
function updateFitQty(){
    // 弹出模态窗带有表格显示对应的多次入库的数据
    let kGrid = $('#e_grid_finished').data('kendoGrid');
    let selectedGridRows = kGrid.select();
    let selected = [];
    selectedGridRows.each(function () {
        let dataItem = kGrid.dataItem($(this));
        selected.push(dataItem);
    });

    if (selected == undefined || selected.length <= 0) {
        $.messager.alert('提示', '在【已完成】页面中选中行后再使用本功能!', 'warning');
        return;
    }
    // 只可以选中一行进行操作
    if( selected instanceof Array && selected.length > 1) {
        $.messager.alert('提示', '只可选中一行进行操作！', 'warning');
        return
    }

    // console.log('在已完成标签页中选中的行是：',selected);
    let updateInputDataSource = [];
    let planId = selected[0]['id'] || 0; // 如果选中了多行则取第一行
    refreshApi(selected[0]);// 根据选中行刷新获取对应的 api
    // console.log('生产计划明细主键：',planId);
    $.ajax({ // 请求获取已入库数据
        contentType: "application/json;charset=UTF-8",
        url: `productOrderBill/selectByPlanId/${planId}`,
        traditional: true,
        async: false,
        type: 'GET',
        dataType: 'json',
        success: function (data) {// 请求后端对应的成品入库明细数据
            if (!data.success) {// 后端没有正常获取数据
                $.messager.alert('提示', data.message, 'warning');
                return
            }
            updateInputDataSource = data.data;// 后端返回的 ResponseResult
        },
        error: function () {
            $.messager.alert('提示', '根据选中生产计划查询获取对应的成品入库数据时出现异常！', 'warning')
        }
    });


    // let dialogId = `dialog${Math.floor(Math.random() * 10000)}`;
    // let datagridId = `datagrid${Math.floor(Math.random() * 10000)}`;

    // 修改入库数模态窗模板代码
    // let div = $(`<div id="${dialogId}" class="easyui-dialog">
    //
    //             <div class="input-group">
    //                 <input class="easyui-textbox" id="planQty" name="planQty" data-options="label:'计划数量：', labelAlign:'right', readonly:true,">
    //                 <input class="easyui-textbox" id="fitQty" name="fitQty" data-options="label:'贴合数量：', labelAlign:'right', readonly:false,">
    //                 <input class="easyui-textbox" id="qualifiedQty" name="qualifiedQty" data-options="label:'良品数量：', labelAlign:'right', readonly:true,">
    //             </div>
    //             <table id="${datagridId}"></table>
    //
    //             </div>`);
    // $(div).appendTo($('body'));

    let dialogId = 'updateQtyDialog';
    let datagridId = 'updateQtyGrid';

    // 模态窗中采用表格显示成品入库数据
    $(`#${dialogId}`).dialog({
        closed: false,
        width: 1000,
        height: 500,
        modal: true,
        resizable: true,
        title: '已入库成品',
        iconCls: 'icon-edit',
        onClose: function () {
            //$(this).dialog('destroy');
        },
        buttons: [
            {
            text: '保存',
            iconCls: 'icon-save',
            handler: e => {
                $(`#${datagridId}`).edatagrid('saveRow');
                let rows = $(`#${datagridId}`).edatagrid('getRows') || [];
                let errCount = rows.filter(item => item['amount'] <= 0).length;
                if (errCount > 0) {
                    $.messager.alert('提示', '数量不能小于0', 'error');
                    return;
                }

                // 修改成品入库明细数据同时更新对应计划的良品数量
                // 工藤有修改成品入库明细数据的权限所以可以操作
                // 车间账号 2001 没有修改成品的权限所以无法使用本功能
                $.ajax({
                    // url: 'productOrderBill/updateRKAndPlan',
                    // 2023年2月12日新增“执行计划”时修改本接口
                    // “修改计划良品数”调整为修改“执行计划”的良品数
                    url: 'productOrderBill/updateRKAndExecPlan',
                    type: 'POST',
                    dataType: 'json',
                    contentType: 'application/json',
                    data: JSON.stringify(rows)
                }).then(function (data) {
                    if (data.success) {
                        $.messager.show({title: '提示', msg: data.message});
                        $(`#${dialogId}`).dialog('close');
                        //loadForm($('#id').textbox('getValue'));
                    } else {
                        $.messager.alert('提示', data.message, 'error');
                    }
                });

                // 更新生产计划明细数据的贴合数量
                // 本请求应用“取消完工”角色下的“生产计划登记页”的“审核”功能
                // 所以车间账号也没有权限修改原始计划的贴合数量，工藤的账号可以 2021年8月19日 13:01:28
                const fitQty = $('#fitQtyUpdate').textbox('getValue');
                const execPlanDetail = {'id':planId,'fitQty':fitQty};
                setTimeout(function(){
                    $.ajax({
                        // url: 'execPlanDetail/updateSelectiveJson',
                        url: urlUpdateSelectiveJson,
                        type: 'POST',
                        dataType: 'json',
                        contentType: 'application/json',
                        data: JSON.stringify(execPlanDetail)
                    }).then(function (data) {
                        if (data.success) {
                            $.messager.show({title: '提示', msg: '贴合数量修改成功！'});
                            $(`#${dialogId}`).dialog('close');
                            //loadForm($('#id').textbox('getValue'));
                        } else {
                            $.messager.alert('提示', data.message, 'error');
                        }
                    });
                },300)
            }
        }, {
            text: '取消',
            iconCls: 'icon-cancel',
            handler: e => {
                $(`#${dialogId}`).dialog('close');
            }
        }]
    });

    // “修改入库数”弹出模态窗的表格列配置
    $(`#${datagridId}`).edatagrid({
        data: [],
        striped: true,
        fit: true,
        sortable: true,
        rownumbers: true,
        remoteSort: false,
        showFooter: true,
        singleSelect: true,
        destroyMsg: {
            norecord: {
                title: '警告',
                msg: '未选中任何数据'
            },
            confirm: {
                title: '确认',
                msg: '确定删除吗?删除后不可恢复!'
            }
        },
        columns: [[
            // {title: '编号', field: 'id', hidden: true, width: 50, align: 'center', halign: 'center'},
            // {title: '外键', field: 'parentId', hidden: true, width: 50, align: 'center', halign: 'center'},
            {
                title: '存货编码',
                field: 'productCoded',
                width: 170,
                align: 'center',
                halign: 'center',
            },
            {
                title: '存货名称',
                field: 'productName',
                width: 180,
                align: 'center',
                halign: 'center',
            },
            {
                title: '规格型号',
                field: 'specification',
                width: 150,
                align: 'center',
                halign: 'center',
            },
            {
                title: '入库数量',
                field: 'amount',
                width: 100,
                align: 'right',
                halign: 'center',
                formatter: (v, r, i) => {
                    return v ? parseFloat(v).toFixed(0) : '';
                },
                editor: {type: 'numberbox', options: {required: true, precision: 0}}
            }
        ]],
        onLoadSuccess: function (data) {
            let rows = data.rows;
            $(this).edatagrid('reloadFooter', [{
                productCoded: '合计',
                amount: rows.reduce(function (prev, curr) {
                    return prev += (curr['amount'] ? parseFloat(curr['amount']) : 0);
                }, 0)
            }])
        },
        onEdit: function (index, row) {
        },
        onAdd: function (index, row) {
        },
        onSave: function (index, row) {
            currentEditIndex = undefined;
            let rows = $(this).edatagrid('getRows') || [];
            $(this).edatagrid('reloadFooter', [{
                productCoded: '合计',
                amount: rows.reduce(function (prev, curr) {
                    return prev += (curr['amount'] ? parseFloat(curr['amount']) : 0);
                }, 0)
            }])
        },
        onResizeColumn: function (f, w) {
            columnResizeEvent($('body').data('menu_id'), f, w, null, null, '_split');
        },
    });
    setDatagridColumnOpts($('body').data('menu_id'), $(`#${datagridId}`), null, undefined, '_split');
    $(`#${datagridId}`).edatagrid('loadData', updateInputDataSource);

    // 填充数据：计划数量、贴合数量、良品数量
    fillUpdateFitQty(selected[0]);

}


function test01(){
    let rows = $('#e_grid').edatagrid('getRows') || [];
    console.log(rows);
}

/**
 * 2021年10月8日 09:50:08 chanchaw
 * 构建产品小标签打印参数，传入字符串类型 tagPath ，一般为：tags/TOTO_tiny.cpt
 * 根据 / 后面的报表文件名称构建打印参数。TOTO的小标签要求传入参数是生产计划明细数据主键
 * 其他产品的小标签要求参数是存货档案
 * reportlet: record['tagPath'],
 * pfCoded: productCoded
 * 返回0表示采用默认方式 - 老方式 - 传入存货编码作为参数
 * 返回1表示 2021年10月8日 10:06:21 为TOTO 制作的产品标签，要求传入生产计划明细数据主键
 */
function tinyTagParamMode(tagPath){
    if( !tagPath ) return null;
    const strArray = tagPath.split("/");
    const reportFileName = strArray.length > 1 ? strArray[1] : strArray[0];
    if( "TOTO_tiny.cpt" === reportFileName || "TOTO_tiny8.cpt" === reportFileName )
        return 1;
    return 0;
}

/**
 * 2021年10月11日 09:30:22 chanchaw
 * 2023年2月15日 本方法只用于打印小标签
 * @param tagPath 标签 cpt 文件所在路径，例如：tag/TOTO.cpt
 * @param id 打印成品现品票报表时传入的参数id - 生产计划明细主键
 * @param productCoded 成品存货编码
 * @returns {{reportlet: *, pfCoded: *}|{reportlet: *, id: *}|null} 提供给 FineReport 打印用的参数
 */
function getRptParam(tagPath,id,productCoded,category,execPlan){
    if( !tagPath ) return null;
    let rptParam = {};
    // 2021年11月24日 08:27:46 chanchaw
    // 注释下面一行代码，本次更新开始以分类区分传参的方式 - 之前是以模板文件名区分
    // if( tinyTagParamMode(tagPath) === 1 ){
    if( category === 1 ) {// 打印TOTO小标签
        rptParam = {reportlet: tagPath, id: id};
    }else{
        // 打印常规小标签
        // 2022年6月11日 19:39:18 为了做小标签 “中外制药 10枚标签” 时追加了传递参数 salesPlanReportDtlId - sales_plan_report_dtl.id
        rptParam = {reportlet: tagPath, pfCoded: productCoded,salesPlanReportDtlId:id};
    }

    // 2023年2月15日制作执行计划后追加的参数：
    rptParam.detailId = id;
    rptParam.execPlan = execPlan;
    return rptParam;
}

// 返回 true 表示跳过扫码 - 即使存货档案中设置了强制扫码也可跳过
function cheat4ScanCode(){
    const userName = getLocalStorage_userName();
    // return userName === '工藤荣峰'? true : false;
    return isAdmin(userName);
}

// 保存函数请求存货档案 promise 对象之后调用本函数
// 传入响应对象，本函数检测良品数量向上的浮动率是否合法
// 参数 productFileRes.data = Java.Model.ProductOrderSavePreData
// 返回类型：Java.Model.ResponseResult
// private boolean success;
// private String responseCode;
// private T data;
// private String message;
function checkFloatPercentage(productFile,postdata){
    return new Promise((resolve,reject)=>{
        const ret = {success:true,message:'没有设置提示文案',data:productFile};
        $.ajax({
            // async: false,
            type : "POST",
            contentType: "application/json;charset=UTF-8",
            data: JSON.stringify(postdata),
            url : "execPlanDetail/getSavePredata"
        }).then(preDataRes => {
            if(!preDataRes.success){
                $.messager.alert('提示', preDataRes.message, 'error');
                ret.success = false;
                reject();
            }

            // 请求来数据模型：
            // BigDecimal planQty;// 计划数量
            // BigDecimal qualifiedQty;// 累计良品数量
            // Integer floatPercentage;// 上浮百分比，5则表示上浮5%之内都是合法的
            // Integer promptGrade;// 提示等级，0不提示，1仅提示，2强制不可保存
            const preData = preDataRes.data;
            const promptGrade = preDataRes.data.promptGrade;
            if(promptGrade === 0)// 不需要提示则直接退出
                resolve(ret);


            // 累计良品数量没有超过计划数量则不需要验证直接返回
            const planQty = preData.planQty || 0;
            const qualifiedQty = preData.qualifiedQty || 0;
            const diff = qualifiedQty - planQty;
            if(diff<=0)
                resolve(ret);

            const floatPercentageChecked = diff / (planQty === 0 ? 1 : planQty) * 100;
            if(floatPercentageChecked > preData.floatPercentage){// 超过浮动率
                const tip0 = `计划数量${planQty}，累计入库良品数量${qualifiedQty} \n 标准浮动率${preData.floatPercentage}，实际浮动率${floatPercentageChecked}`;
                const tip1 = `${tip0} \n 不可入库！`;
                const tip2 = `${tip0} \n 是否仍然入库？`;
                if(promptGrade == 2){// 强制不允许保存
                    $.messager.alert('提示', tip1, 'error');
                    reject();
                }else {
                    $.messager.confirm('提示', tip2, r => {
                        if (r) resolve(ret);
                        else reject();
                    })
                }
            }else{
                resolve(ret);
            }
        },()=>{
            $.messager.progress('close');
            $.messager.alert('提示', '检查良品数量浮动率时出现异常！', 'error');
        });
    });
}

function checkFloatPercentage01(data,postdata){
    return $.ajax({
        type : "POST",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(postdata),
        // url : "execPlanDetail/getSavePredata"
        url: urlGetSavePredata
    });
}

function getDrawingFileLink(fileName){
    return '/xzy/drawing/' + fileName;
}

// DB中字段 filename_rename + filename_original的后缀名构建为文件的下载名称
// 如果没有 rename 则返回原始文件名
function getDownloadFileName(rowData){
    const filenameOriginal = rowData['filename_original'];
    const filenameRename = rowData['filename_rename'];
    const extension = getFileExtension(filenameOriginal);
    let downloadFileName = '';
    if( !filenameRename || filenameRename.length<=0 )
        downloadFileName = filenameOriginal;
    else
        downloadFileName = filenameRename + '.' + extension;
    return downloadFileName;
}

// 传入“未完工”表格选中的行，根据行数据字段 execPlan 返回是否是执行计划
function isExecPlan(selectedRow){
    if(!selectedRow) return true;
    const ret = parseInt(selectedRow.execPlan||0);
    return ret === 1 ? true : false;
}

// function getSaveUrl(selectedRow){
//     return isExecPlan(selectedRow) === true ? 'execPlanDetail/updateAccumulate' : 'salesPlanReportDtl/updateAccumulate';
// }

// 传入“未完工”表格中选中的行，更新多出请求后台api的url
function refreshApi(selectedRow){
    if(isExecPlan(selectedRow)){// 是执行计划
        urlDialogInit = `execPlanDetail/queryByPk/${selectedRow.id}`;
        urlDialogSave = 'execPlanDetail/updateAccumulate';
        urlDialogUpdateProjectName = 'execPlanMain/updateProjectName';
        urlFinish = 'execPlanMain/finished';
        urlFinishCancel = 'execPlanMain/finished/cancel';
        urlWorkshopUpdate = 'execPlanDetail/workshop/updateSelective';
        urlGridUFMove = 'execPlanDetail/move';
        urlGridFinishedPrintUpdate = 'execPlanDetail/updateSelective';
        urlUpdateSelectiveJson = 'execPlanDetail/updateSelectiveJson';
        urlGetSavePredata = 'execPlanDetail/getSavePredata';
    }else{
        urlDialogInit = `salesPlanReportDtl/queryByPk/${selectedRow.id}`;
        urlDialogSave = 'salesPlanReportDtl/updateAccumulate';
        urlDialogUpdateProjectName = 'salesPlanReport/updateProjectName';
        urlFinish = 'salesPlanReport/finished';
        urlFinishCancel = 'salesPlanReport/finished/cancel';
        urlWorkshopUpdate = 'salesPlanReportDtl/workshop/updateSelective';
        urlGridUFMove = 'salesPlanReportDtl/move';
        urlGridFinishedPrintUpdate = 'salesPlanReportDtl/updateSelective';
        urlUpdateSelectiveJson = 'salesPlanReportDtl/updateSelectiveJson';
        urlGetSavePredata = 'salesPlanReportDtl/getSavePredata';
    }

    //console.log(`urlDialogInit:${urlDialogInit}`);
    //console.log(`urlDialogSave:${urlDialogSave}`);
    //console.log(`urlDialogUpdateProjectName:${urlDialogUpdateProjectName}`);
}

function getSelectedRow4Print(){
    const selectedTabIndex = getSelectedIndex();
    if(selectedTabIndex === 0){// 当前处于未完工标签页
        selectedRow4print = $('#e_grid').datagrid('getSelected');
    }else{// 已完工标签页
        let kGrid = $('#e_grid_finished').data('kendoGrid');
        selectedRow4print = kGrid.dataItem(kGrid.select());
    }
}